简体   繁体   中英

How to determine the difference between two dates in years and months in MYSQL?

The database holds records for people of all ages including children under the age of 1 where months are important.

Using

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

The problem you get is anyone < 1 year shows up as 0;

Using

SELECT TIMESTAMPDIFF(MONTH, dob, CURDATE()) AS age; 

Anyone over the age of 1 just shows up in months so a 43 year old will have an age of > 500 months

Using

SELECT TIMESTAMPDIFF(MONTH, dob, CURDATE()) / 12 AS age; 

You can get some results like .25 for a 3 month old or 43.25 for someone who is > 43

What I am trying to achieve is something like

  • 43y 3m
  • 0y 3m
  • or even just 3m for those < 1 year

How can something like this be expressed in a mysql query?

 SELECT IF(TIMESTAMPDIFF(MONTH, dob, CURDATE())>12,TIMESTAMPDIFF(MONTH, dob, CURDATE())/12+ 'yeasrs old' , TIMESTAMPDIFF(MONTH, dob, CURDATE())+'months old')

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