Languages
[Edit]
EN

MySQL - difference between two dates

6 points
Created by:
Marcino
360

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 from 01 to 12),
  • DD - day number (from 01 to 31 - depending on month),
  • HH - hour number (from 00 to 24),
  • MM - minute number (from 00 to 59),
  • SS - second number (from 00 to 59).

 

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:

MySQL - difference calculation result between two dates
MySQL - difference calculation result between two dates

Note:

Both of the above queries give the same result (difference between 2021-01-08 and 2021-01-05 - 3 days). They don't take time into account.

Related posts

MySQL - dates

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join