Get difference in years between two dates in MySQL as an integer

Try:

SELECT 
  DATE_FORMAT(FROM_DAYS(TO_DAYS(NOW())-TO_DAYS(birth_date)), '%Y')+0
  AS age FROM student;

The accepted answer is almost correct, but can lead to wrong results.

In fact, / 365 doesn't take into consideration leap years, and can lead to falsy results if you compare a date that has the same day&month than the birthdate.

In order to be more accurate, you have to divide it by the average days in years for 4 years, aka (365 * 4) + 1 (the leap year every 4 years) => 365.25

And you will be more accurate :

select id, floor(datediff(curdate(),birth_date) / 365.25) from student

Tested for one of my project and it's working.


select id, floor(datediff(curdate(),birth_date) / 365)
from student

What about flooring the result to be an integer?


For anyone who comes across this:

another way this can be done is:

SELECT TIMESTAMPDIFF(YEAR, date_of_birth, CURDATE()) AS difference FROM student

For differences in months, replace YEAR with MONTH, and for days replace YEAR with DAY

Hope that helps!

Tags:

Mysql