How to use the MySQL DATEDIFF() function
The DATEDIFF()
function in MySQL is used to calculate the difference between two dates in terms of a specified unit like days, weeks, months etc.
The DATEDIFF()
function in MySQL is used to calculate the difference between two dates in terms of a specified unit like days, weeks, months etc.
Syntax
The syntax for DATEDIFF()
is:
DATEDIFF(date1, date2, unit)
Where:
date1
anddate2
are the dates to calculate difference betweenunit
is the unit of difference, like ‘DAY’, ‘WEEK’, ‘MONTH’ etc.
Examples

Get difference in days between two dates:
SELECT DATEDIFF('20230120', '20230105', 'DAY');
Returns a difference of 15 days.

Calculate weeks between two dates:
SELECT DATEDIFF('20230220', '20230128', 'WEEK');
Returns a difference of 3 weeks.

Get months difference between two dates:
SELECT DATEDIFF('20230505', '20230215', 'MONTH');
Returns a difference of 2 months.

Calculate years difference between two dates:
SELECT DATEDIFF('20250728', '20230305', 'YEAR');
Returns a difference of 2 years.

Get difference by day name:
SELECT DATEDIFF('20230115', '20230108', 'DAYOFYEAR');
Returns a difference of 7 days.
Other Similar Functions
TIMEDIFF()
 Time difference between two timesTIMESTAMPDIFF()
 Difference between timestampsTO_DAYS()
 Convert date to daysLAST_DAY()
 Last day of month for a date
So DATEDIFF()
provides a convenient way to calculate the difference between two dates in MySQL.