The correct algorithm for precise age calculation, handling leap years, and why simple subtraction gives wrong results.
The naive formula — current year minus birth year — gives wrong results in two cases: (1) when your birthday hasn't occurred yet this year, and (2) whenever you need months and days, not just years.
Example: Someone born September 15, 1990. On September 1, 2025: they are still 34, not 35 (birthday not yet reached). Simple subtraction (2025 - 1990 = 35) is wrong by 1 year.
Birth date: March 15, 1990 Today's date: February 10, 2025 Step 1: Years Current year - birth year = 2025 - 1990 = 35 But Feb 10 is before Mar 15, so birthday hasn't happened yet Years = 35 - 1 = 34 Step 2: Months Current month - birth month = 2 - 3 = -1 Since negative, add 12 and we already subtracted a year above Months = -1 + 12 = 11 Step 3: Days Days in previous month (January) = 31 Current day + (days in last month - birth day) = 10 + (31 - 15) = 10 + 16 = 26 Result: 34 years, 11 months, 26 days
function calculateAge(dob) {
const birth = new Date(dob);
const now = new Date();
let years = now.getFullYear() - birth.getFullYear();
let months = now.getMonth() - birth.getMonth();
let days = now.getDate() - birth.getDate();
if (days < 0) {
months--;
days += new Date(now.getFullYear(), now.getMonth(), 0).getDate();
}
if (months < 0) {
years--;
months += 12;
}
return { years, months, days };
}