Select Age In Years (or Months If Under 2) From Birthday
Join the DZone community and get the full member experience.Join For Free
The following SQL query will select the age in years for a user from a date field called birthday. If that age is under 2 years old, it will set age to the number of months with the string "mos." concat at the end.
SELECT IF ( DATEDIFF(NOW(), birthday) < 730, CONCAT( FLOOR(DATEDIFF(NOW(), birthday)/30), ' mos.'), DATE_FORMAT(FROM_DAYS(TO_DAYS(NOW())-TO_DAYS(birthday)), '%Y')+0 ) as age FROM users
Opinions expressed by DZone contributors are their own.