JavaScript Calculate Age From Date Code Snippet

function calcAge(dobStr) {
  // 1: create a new `Date` object from `dobStr`
  const birthDate = new Date(dobStr);
  // 2: create a new `Date` object for "today"
  const today = new Date();

  // 3: calculate difference in years between birth year and current year
  let age = today.getFullYear() - birthDate.getFullYear();
  // 4: calculate difference in months between birth month and current month
  const monthDifference = today.getMonth() - birthDate.getMonth();

  if (
    // 5.1: current month is earlier than the birth month?
    monthDifference < 0
    // 5.2: or, same month but current day is earlier than birth day?
    || (monthDifference === 0 && today.getDate() < birthDate.getDate())
  ) {
    // 5.3: subtract `1` from the age
    age--;
  }

  // 6: return calculated age
  return age;
}
console.log(calcAge('1980-05-05'));
console.log(calcAge('1910-07-16'));
console.log(calcAge('2020-02-24'));
console.log(calcAge('2023-01-01'));
// ...

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.