Find the difference between two datetime values with MySQL?

MySQLMySQLi Database

To find the difference between two datetime values, you can use TIMESTAMPDIFF(). Let us first create a table −

mysql> create table DemoTable
   -> (
   -> DueDatetime1 datetime,
   -> DueDatetime2 datetime
   -> );
Query OK, 0 rows affected (0.86 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('2019-10-26 19:49:00','2019-10-26 17:49:00');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('2019-10-26 08:00:00','2019-10-26 13:00:00');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('2019-10-26 06:50:00','2019-10-26 12:50:00');
Query OK, 1 row affected (0.68 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+---------------------+---------------------+
| DueDatetime1        | DueDatetime2        |
+---------------------+---------------------+
| 2019-10-26 19:49:00 | 2019-10-26 17:49:00 |
| 2019-10-26 08:00:00 | 2019-10-26 13:00:00 |
| 2019-10-26 06:50:00 | 2019-10-26 12:50:00 |
+---------------------+---------------------+
3 rows in set (0.00 sec)

Here is the query to implement timestampdiff() and find the difference between two dates −

mysql> select abs(timestampdiff(minute,DueDatetime1,DueDatetime2)) from DemoTable;

This will produce the following output −

+------------------------------------------------------+
| abs(timestampdiff(minute,DueDatetime1,DueDatetime2)) |
+------------------------------------------------------+
|                                                  120 |
|                                                  300 |
|                                                  360 |
+------------------------------------------------------+
3 rows in set (0.00 sec)
raja
Published on 12-Dec-2019 11:59:04
Advertisements