Here’s an example function in JavaScript that takes a birth date in the format “YYYYMMDD” as an input and calculates the age:

function calculateAge(birthDate) {
  var today = new Date();
  var birth = new Date(birthDate.substring(0,4), birthDate.substring(4,6) - 1, birthDate.substring(6,8));
  var age = today.getFullYear() - birth.getFullYear();
  var m = today.getMonth() - birth.getMonth();
  if (m < 0 || (m === 0 && today.getDate() < birth.getDate())) {
    age--;
  }
  return age;
}

You can call this function by passing in a birth date string in the format “YYYYMMDD”, like so:

var birthDate = "19900101";
var age = calculateAge(birthDate);
console.log(age);

It will return the age of the person.

Please note that the above code snippet is assuming that the birthdate is a valid date and it’s not handling any exception which might occur if passed date is not valid.

Also Read:

Categorized in: