Back to articles
How to Calculate Age Correctly: The Edge Cases Every Developer Misses

How to Calculate Age Correctly: The Edge Cases Every Developer Misses

via Dev.to TutorialHAU

Calculating someone's age sounds like a five-minute task: function getAge ( birthday ) { const diff = Date . now () - new Date ( birthday ). getTime (); return Math . floor ( diff / ( 365.25 * 24 * 60 * 60 * 1000 )); } Ship it. Except this gives wrong answers on certain dates and can be off by a full year around birthdays. Let's fix it. Why the Division Approach Fails Dividing milliseconds by an "average year" ( 365.25 days ) is imprecise because: Leap years don't distribute uniformly — they cluster every 4 years Someone born January 1, 2000 is not quite 26.25 years old on March 24, 2026 The rounding can flip in the wrong direction around the birthday // Test: birthday Jan 1, today March 24 2026 getAge ( ' 2000-01-01 ' ); // Should be 26, might return 25 or 26 depending on leap year timing The Correct Calendar-Based Approach Age in years is a calendar concept, not a duration in milliseconds. Calculate it as a calendar difference: function getAge ( birthdayStr ) { const today = new Date

Continue reading on Dev.to Tutorial

Opens in a new tab

Read Full Article
6 views

Related Articles