Now you can listen to this article with the Online Text Reader


JavaScript Function to Calculate Age from Date of Birth





This function written in JavaScript calculates the age of a person. The input data is the month, the day, and the full year this person was born. All this data must be written using numbers, the month being a number from 1 to 12.

This is the function:

<script type="text/javascript">

function calculateAge(birthMonth, birthDay, birthYear)
{
  todayDate = new Date();
  todayYear = todayDate.getFullYear();
  todayMonth = todayDate.getMonth();
  todayDay = todayDate.getDate();
  age = todayYear - birthYear;

  if (todayMonth < birthMonth - 1)
  {
    age--;
  }

  if (birthMonth - 1 == todayMonth && todayDay < birthDay)
  {
    age--;
  }
  return age;
}

</script>


Next, we will see an example of how to call this function. It calculates the age of a girl born on November the 2nd of 1992.

<script type="text/javascript">

document.write("She is " + calculateAge(11,2,1992)
+ " years old" );

</script>

Since this function adds a year of age only once the date of the birthday has arrived or passed, it works perfectly fine calculating the age of people born on February the 29th of leap years.

Enjoy!

Share this article:



JavaScript Manual >> JavaScript Function to Calculate Age





© Copyright 2010-2018 ROM Cartridge



Books to Read and Listen to Online