Calculating Age as of a Date: How Leap Year Complicates Things
I am currently working on an application that must take a user's birthdate, and the date of a particular event, and use them to calculate the user's age when the event occurred.
MySQL has a built in function called DATEDIFF() that returns the number of days between any two dates. So to calculate the user's age when the event occured, we just use DATEDIFF() to find the number of days between event_date, and user_birthdate, and then divide by 365 and throw out the remainder, right?
Well, thats what I thought anyway. But in testing, it became obvious that if the event month/day was only a few days before the user's birthdate month/day, the answer was always one year more than it should have been.
Enter leap year. MySQL is smart enough to factor in leap years, so some years have 366 days between the same two calendar days. So to calculate age correctly, just divide by 365.25 instead of 365!
FLOOR(DATEDIFF(event_date,user_birthdate)/365.25) AS user_age_at_event_calcSometimes it is the simplest things that are the hardest!
Comments
Post new comment