How to calculate the difference between time in different MySQL columns?

MySQLMySQLi Database

You can use TIME_FORMAT(). Let us first create a table −

mysql> create table DemoTable
   -> (
   -> PunchIn time,
   -> PunchOut time,
   -> Launch time
   -> );
Query OK, 0 rows affected (0.50 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('9:00','6:00','1:00:00');
Query OK, 1 row affected (0.19 sec)

mysql> insert into DemoTable values('9:30','6:10','00:30:00');
Query OK, 1 row affected (0.21 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+----------+----------+----------+
| PunchIn  | PunchOut | Launch   |
+----------+----------+----------+
| 09:00:00 | 06:00:00 | 01:00:00 |
| 09:30:00 | 06:10:00 | 00:30:00 |
+----------+----------+----------+
2 rows in set (0.00 sec)

Here is the query to make a correct time calculation −

mysql> SELECT TIME_FORMAT(TIMEDIFF(TIMEDIFF(PunchIn,PunchOut), Launch), '%H:%i') as TimeDiff from DemoTable;

Output

+----------+
| TimeDiff |
+----------+
| 02:00    |
| 02:50    |
+----------+
2 rows in set (0.00 sec)
raja
Published on 10-Jul-2019 11:50:48
Advertisements