Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to calculate age from a date of birth

Short answer

Subtract the years, and subtract one more if the birthday has not come yet this year:

const getAge = (birth, today = new Date()) => {
  let age = today.getFullYear() - birth.getFullYear();
  const hadBirthday =
    today.getMonth() > birth.getMonth() ||
    (today.getMonth() === birth.getMonth() && today.getDate() >= birth.getDate());
  if (!hadBirthday) age--;
  return age;
};
 
console.log(getAge(new Date(1990, 5, 15), new Date(2025, 5, 14)));
console.log(getAge(new Date(1990, 5, 15), new Date(2025, 5, 15)));

Output:

34
35

From a string

A date from a form comes as a string like 1995-12-01. Split it into numbers and build a local date:

const [year, month, day] = '1995-12-01'.split('-').map(Number);
const birth = new Date(year, month - 1, day);
 
console.log(birth.toDateString());

Output:

Fri Dec 01 1995

Common mistake

Dividing the difference in milliseconds by the length of a year gives a slightly wrong age near the birthday because of leap years:

const birth = new Date(2000, 2, 1);
const today = new Date(2025, 1, 28);
const years = (today - birth) / (365 * 24 * 60 * 60 * 1000);
 
console.log(Math.floor(years));

Output:

25

The person is still 24, but the formula already shows 25.

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.