简体   繁体   English

MySQL年龄从出生日期开始-TIMESTAMPDIFF()

[英]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. 现在,人们想出了许多功能来确定从出生日期算起的准确年龄,同时还要考虑leap年和其他因素。 However the MySQL documentation offers a very simple solution: 但是, MySQL文档提供了一个非常简单的解决方案:

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 . 它似乎比简单的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 :) 已经有bug了,但是如果您说最新的MySQL版本为6年左右,则应该放心使用它:)

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=16697

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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