📅Date & Time

Exact Age Calculation

Patterns for calculating age based on birthdate and current date.

Explanation

Calculating age requires handling leap years and comparing the current month/day to the birth month/day.

Examples

Born 1990
Output
34 years
Infant
Output
6 months, 12 days

Code Examples

JavaScript
function calculateAge(birthday) {
  const ageDifMs = Date.now() - birthday.getTime();
  const ageDate = new Date(ageDifMs);
  return Math.abs(ageDate.getUTCFullYear() - 1970);
}

💡 Tips

  • Check if the birthday has already occurred this year
  • Handle February 29th for leap-year babies
  • For small ages, use months or weeks

⚠️ Common Pitfalls

  • Simple year subtraction is often off by 1
  • Timezone changes on birth day can be tricky