Categories
JavaScript Answers

How to Calculate a Person’s Age from Someone’s Birthday with JavaScript?

Spread the love

To calculate a person’s age from someone’s birthday with JavaScript, we can use native JavaScript date methods.

For instance, we can write:

const getAge = (d1, d2 = new Date()) => {
  const diff = d2.getTime() - d1.getTime();
  return Math.floor(diff / (1000 * 60 * 60 * 24 * 365.25));
}

console.log(getAge(new Date(1988, 10, 3)));

We create the getAge function that takes 2 dates d1 and d2 .

Then we subtract the timestamps of them that we got with getTime with:

const diff = d2.getTime() - d1.getTime();

And then we divide diff with 1000 * 60 * 60 * 24 * 365.25 to convert diff to the number of years differences, which is the person’s age.

Therefore, the console log should log 32.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *