I am trying to calculate how old is a person in a database.
Let\'s suppose to have this simple table:
student(id, birth_date);
Where
I have not enough reputation to add comment to an answer by Rat-a-tat-a-tat Ratatouille to improve his code. Here is the better SQL-query:
SELECT IFNULL(TIMESTAMPDIFF(YEAR, birthdate, CURDATE()), YEAR(CURDATE()) - YEAR(birthdate)) AS age
This is better because sometimes "birthdate" may contain only year of birth, while day and month is 0. If TIMESTAMPDIFF() returns NULL, we can find rough age by subtracting the current year from the year of birth.
I'd suggest this:
DATE_FORMAT(NOW(),"%Y")
-DATE_FORMAT(BirthDate,'%Y')
-(
IF(
DATE_FORMAT(NOW(),"%m-%d") < DATE_FORMAT(BrthDate,'%m-%d'),
1,
0
)
) as Age
This should work with leap-years very well ;-)
Try:
SELECT
DATE_FORMAT(FROM_DAYS(TO_DAYS(NOW())-TO_DAYS(birth_date)), '%Y')+0
AS age FROM student;
This works, even taking in account leap years!
select floor((cast(date_format('2016-02-29','%Y%m%d') as int) - cast(date_format('1966-03-01','%Y%m%d') as int)/10000);
Just be sure to keep the floor()
as the decimal is not needed
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!
Why not use MySQL's FLOOR() function on the output from your second approach? Any fractions will be dropped, giving you the result you want.