简体   繁体   中英

MySQL age from date of birth - TIMESTAMPDIFF()

Yes very similar has been asked before, but bear with me.

Now there are many functions people come up with to determine an accurate age from date of birth taking into account leap years and whatnot. However the MySQL documentation offers a very simple solution:

SELECT TIMESTAMPDIFF(YEAR, dob, CURDATE()) AS age

This seems to work for all the dates I throw at it. However the documentation states nothing about the correctness of this or how it calculates the difference. It does seem to be smarter than a simple diff/365.25 .

Here's some examples:

('1992-08-12', '3009-08-12') => 1017 - Correct
('1992-08-12', '3009-08-11') => 1016 - Correct
('1992-02-29', '3009-03-01') => 1017 - Correct
('1992-02-29', '3009-02-28') => 1016 - Correct

Looks pretty correct to me and that is a heck of a long time for minor miscalculations to stack up in.

My question to you, is it safe to use this? Can you provide a set of dates this will give an incorrect result for? (Not interested in units smaller than a day)

There has been bugs, but you should feel safe to use it if you have latest say 6 years MySQL version or so :)

some earlier bugs e.g. month diff of dates:
TS1 = '2006-01-21 19:52:05'
TS2 = '2007-01-21 18:30:14'

which gave 0, and not 12.

http://bugs.mysql.com/bug.php?id=16697

http://bugs.mysql.com/bug.php?id=25994

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM