Age Calculation and Date Math: Handling Years, Months, and Days
Calculating an age sounds trivial until leap years and time zones get involved. After building a date calculator, here is. Calculating an age sounds trivial. Subtract the birth year from the current year and you are done, until you remember that the birthday might not have passed yet this year, that leap years add a day, and that time zones can shift the date. After building an age calculator and a date difference tool, I learned that date math has more edge cases than I expected. Here is what I handle and why. The Basic Age Calculation The simple version of age is current year minus birth year. If today is June 22, 2026, and the birth date is March 15, 1990, the age is 2026 minus 1990, which is 36. This works because the birthday has already passed this year. If the birthday is July 15, 1990, the simple subtraction gives 36, but the person has not turned 36 yet. They are still 35 until July 15. The correct age subtracts one if the birthday has not occurred yet this year. I check the month and day of the birth date against the current month and day. function calculateAge(birth, today) { let age = today.getFullYear() - birth.getFullYear(); const hadBirthday = today.getMonth() > birth.getMonth() || (today.getMonth() === birth.getMonth() && today.getDate() >= birth.getDate()); if (!hadBirthday) age -= 1; return age; } This handles the common case.