0
0
JavascriptHow-ToBeginner · 3 min read

Calculate Age from Date of Birth in JavaScript: Simple Method

To calculate age from a date of birth in JavaScript, create Date objects for the birth date and current date, then subtract the years and adjust if the birthday hasn't occurred yet this year. Use new Date() for the current date and compare months and days to get the exact age.
📐

Syntax

Use the following pattern to calculate age:

  • birthDate: a Date object representing the date of birth.
  • today: a Date object for the current date.
  • Calculate the difference in years, then adjust if the birthday hasn't happened yet this year.
javascript
const birthDate = new Date('YYYY-MM-DD');
const today = new Date();
let age = today.getFullYear() - birthDate.getFullYear();
const monthDiff = today.getMonth() - birthDate.getMonth();
if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
  age--;
}
💻

Example

This example shows how to calculate the exact age from a given date of birth string.

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

console.log(calculateAge('1990-06-15'));
⚠️

Common Pitfalls

Common mistakes include:

  • Not adjusting the age if the birthday hasn't occurred yet this year, which can overstate the age by 1.
  • Using string comparison instead of Date objects, leading to incorrect results.
  • Ignoring time zones which can cause off-by-one errors if the date is near midnight UTC.
javascript
/* Wrong way: No adjustment for birthday */
function wrongAge(dobString) {
  const birthDate = new Date(dobString);
  const today = new Date();
  return today.getFullYear() - birthDate.getFullYear();
}

/* Right way: Adjust if birthday not reached yet */
function correctAge(dobString) {
  const birthDate = new Date(dobString);
  const today = new Date();
  let age = today.getFullYear() - birthDate.getFullYear();
  const monthDiff = today.getMonth() - birthDate.getMonth();
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }
  return age;
}
📊

Quick Reference

Remember these key points when calculating age:

  • Use Date objects for accurate date handling.
  • Subtract birth year from current year.
  • Check if birthday has passed this year to adjust age.
  • Return the final age as a whole number.

Key Takeaways

Create Date objects for birth date and current date to work with real dates.
Subtract birth year from current year, then adjust if birthday hasn't occurred yet this year.
Always compare months and days to avoid overestimating age by one year.
Avoid string comparisons and consider time zones for precise age calculation.