
Date Arithmetic Is Harder Than You Think: Why Calculating Age Is a Real Problem
Quick: how old are you in days? Not approximately. Exactly. Including leap years. Go ahead and try to calculate it. If you reached for a calculator and started multiplying your age by 365, you already got it wrong. Leap years add a day every four years -- except for years divisible by 100, unless they're also divisible by 400. The year 2000 was a leap year. 1900 was not. 2100 won't be either. Date arithmetic looks trivial until you actually try to implement it. Then it becomes one of the most surprisingly complex problems in everyday programming. The naive approach and why it breaks The most common way developers calculate age is something like this: function getAge ( birthDate ) { const today = new Date (); const age = today . getFullYear () - birthDate . getFullYear (); return age ; } This returns the wrong answer for anyone who hasn't had their birthday yet this year. Born on November 15, 1990? On March 20, 2026, this function returns 36. You're actually 35. The "fix" usually looks
Continue reading on Dev.to Webdev
Opens in a new tab

