Back to Snippets
CODE

Calculate Age from Birthdate

Description

Calculates accurate age from birthdate considering month and day

Code

/**
 * Calculate age from birthdate
 * @param birthdate Birthdate (Date object or ISO string)
 * @returns Calculated age in years
 */
function calculateAge(birthdate: Date | string): number {
  const birth = new Date(birthdate);
  const today = new Date();
  
  let age = today.getFullYear() - birth.getFullYear();
  const monthDiff = today.getMonth() - birth.getMonth();
  
  // Adjust age if birthday hasn't occurred yet this year
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
    age--;
  }
  
  return age;
}

// Usage Example
console.log(calculateAge('1990-05-20')); // 34 (if current year is 2024)
console.log(calculateAge(new Date(1990, 4, 20))); // 34

Usage

Useful for user profile pages, age verification, or any application requiring age calculation from birthdate

Tags

Date CalculationAgeUtility Function