How to Calculate Age from Birthdate in JavaScript

08/03/2021

Contents

In this article, you will learn how to calculate age from birthdate in JavaScript.

Calculating age from birthdate in JavaScript

Calculating age from a birthdate is a common requirement in web development, especially when dealing with forms that require users to enter their date of birth. In JavaScript, we can calculate the age from a birthdate using the Date object and some simple math.

Here are the steps to calculate age from a birthdate in JavaScript:

Get the current date using the Date object:

const today = new Date();

Get the birthdate using a date string or a Date object:

const birthdate = new Date('1990-01-01');
// or
const birthdate = new Date(1990, 0, 1);

Calculate the difference between the current date and the birthdate in milliseconds:

const diff = today.getTime() - birthdate.getTime();

Convert the difference to years by dividing it by the number of milliseconds in a year:

const age = Math.floor(diff / (1000 * 60 * 60 * 24 * 365));

Here’s an example function that takes a birthdate string as input and returns the age as a number:

function calculateAge(birthdateStr) {
  const today = new Date();
  const birthdate = new Date(birthdateStr);
  const diff = today.getTime() - birthdate.getTime();
  const age = Math.floor(diff / (1000 * 60 * 60 * 24 * 365));
  return age;
}

Here’s how you can use the function to calculate the age of a person:

const age = calculateAge('1990-01-01');
console.log(age); // Output: 32

In the above example, the calculateAge function takes a birthdate string as input and returns the age as a number. The function uses the steps described above to calculate the age from the birthdate.