Calculate Age

1 parameters

1 of 6

function calculateAge(birthDate)

Calculates age in years from a given birth date

Parameters

Name
Type
Required
Description
birthDatedateRequiredThe birth date to calculate age from

Function Implementation

function calculateAge(birthDate) {
  const today = new Date();
  const birth = new Date(birthDate);
  let age = today.getFullYear() - birth.getFullYear();
  const monthDiff = today.getMonth() - birth.getMonth();
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
    age--;
  }
  return age;
}