EN
MySQL - difference between two dates
6
points
In this article, we would like to show you how to calculate the difference between two dates in MySQL.
Quick solution:
-- SELECT DATEDIFF('to_date','from_date')
SELECT DATEDIFF('YYYY-MM-DD','YYYY-MM-DD');
or (with time):
-- SELECT DATEDIFF('to_date','from_date')
SELECT DATEDIFF('YYYY-MM-DD HH:MM:SS','YYYY-MM-DD HH:MM:SS');
Where:
YYYY- four-digit year format, e.g.2021,MM- month number (counted from01to12),DD- day number (from01to31- depending on month),HH- hour number (from00to24),MM- minute number (from00to59),SS- second number (from00to59).
Practical example
In this example, we will calculate the number of days from 2021-01-05 to 2021-01-08 using DATEDIFF() function.
Query:
SELECT DATEDIFF('2021-01-08','2021-01-05') AS 'difference (in days)';
or:
SELECT DATEDIFF('2021-01-08 09:35:27','2021-01-05 11:22:55') AS 'difference (in days)';
Result:
Note:
Both of the above queries give the same result (difference between
2021-01-08and2021-01-05-3days). They don't take time into account.