How to Calculate Age in JavaScript: 4 Methods That Work

To calculate age in JavaScript, subtract the birth year from the current year, then subtract 1 if the birthday has not happened yet this year. That two-step rule is the whole method, and every correct version of how to calculate age in JavaScript is a variation of it. This guide gives you four methods that actually run — whole years, years-months-days, a working form example, and the timestamp method you should avoid — each with verified output from Node.js 24, plus the February 29 rule and the 0-indexed-month trap that catches most beginners.

how to calculate age in JavaScript

The Short Answer — Copy This Function

If you only need the age in whole years, this is the function to copy. It is the standard birthday-aware method, and it is the one every other method in this guide builds on.

function calculateAge(birthDate) {
  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(new Date(1990, 4, 15))); // 36
console.log(calculateAge(new Date(2000, 1, 29))); // 26

Both outputs were verified by running this code on Node.js v24.22.1 with today set to 15 November 2026. Someone born on 15 May 1990 is 36, and someone born on 29 February 2000 is 26. The rest of this guide explains why each line is there, and where the simpler versions go wrong.

Why Subtracting Years Alone Is Wrong

The first thing to know about how to calculate age in JavaScript is that year subtraction alone is wrong for part of every year. Take someone born on 15 November 1990. On 14 November 2026, plain subtraction gives 2026 − 1990 = 36, but the person is still 35 — their birthday is tomorrow. On 15 November 2026 they turn 36, and only then is 36 correct. The naive version is wrong for everyone, every year, for the stretch between 1 January and their birthday — which is why the month-and-day check in the function above is not optional decoration. Search results for how to calculate age in JavaScript are full of this bug: most snippets show the subtraction and stop there. Any age check that skips it will let a 17-year-old through an 18+ gate for up to a year, or tell a user they are a year older than they are.

Method 1: Whole Years — How to Calculate Age in JavaScript

Method 1 is the function from the short answer, and it is the right default for almost every use: registration forms, age verification, profile displays and eligibility checks. It works in three steps. First, take the difference between the current year and the birth year. Second, compare the current month with the birth month — if the current month is earlier, the birthday has not happened yet, so subtract 1. Third, if the months are equal, compare the day of the month the same way. Months in JavaScript are 0-indexed, so January is 0 and November is 10 — that matters when you construct dates, and the trap is covered in Method 4.

function calculateAge(birthDate) {
  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;
}

Run it against a birthday that has not happened yet this year to see the adjustment work. With today set to 15 February 2026, `calculateAge(new Date(2000, 1, 29))` returns 25, not 26 — the 29 February birthday is still two weeks away, so the function correctly holds the age at 25. Once you know how to calculate age in JavaScript in whole years, the detailed version is a small step from here.

Method 2: Years, Months and Days

When a form or a display needs the exact age — “36 years, 6 months, 0 days” rather than just 36 — calculate each component separately and borrow when a component goes negative. The rule for borrowing days is the one people get wrong: borrow the actual number of days in the previous month, never a fixed 30.

function getDetailedAge(birthDate) {
  const today = new Date();
  let years = today.getFullYear() - birthDate.getFullYear();
  let months = today.getMonth() - birthDate.getMonth();
  let days = today.getDate() - birthDate.getDate();
  if (days < 0) {
    months--;
    const previousMonth = new Date(today.getFullYear(), today.getMonth(), 0);
    days += previousMonth.getDate();
  }
  if (months < 0) {
    years--;
    months += 12;
  }
  return { years, months, days };
}

console.log(getDetailedAge(new Date(1990, 4, 15)));
// { years: 36, months: 6, days: 0 }
console.log(getDetailedAge(new Date(2000, 1, 29)));
// { years: 26, months: 8, days: 17 }

Both outputs are verified runs with today set to 15 November 2026. Someone born on 15 May 1990 is exactly 36 years, 6 months and 0 days old on that date, and someone born on 29 February 2000 is 26 years, 8 months and 17 days old. The same person has lived 13,333 days — the days-lived count our age-in-days guide explains step by step. The same borrow-then-adjust logic powers our whole-months guide, which works out ages in months for babies and toddlers.

Note how the 29 February case is handled: the day comparison (15 − 29 = −14) borrows 31 days from October, giving 17 days, which is the correct count when the birthday is treated as 28 February in a non-leap year. That convention is explained in the February 29 section below.

Method 3: The Timestamp Method — and Why to Avoid It

A common question about how to calculate age in JavaScript is whether to divide the millisecond difference by the length of a year. The code is short, which is why it spreads so easily — and it is wrong in exactly the cases that matter.

function calculateAgeFromMilliseconds(birthDate) {
  const ageInMilliseconds = Date.now() - birthDate.getTime();
  return Math.floor(ageInMilliseconds / (365.25 * 24 * 60 * 60 * 1000));
}

Run on 15 November 2026, the division gives 36.5038 for a 15 May 1990 birthday and 26.7105 for a 29 February 2000 birthday — both floor to the right whole ages, so the method looks correct in a quick test. The problem is the 365.25 divisor: it is an average year length, not a calendar rule, so near a birthday the fraction can tip over a day early or a day late, and daylight saving shifts add another source of drift. The timestamp method is fine for a rough “about 36 and a half” display, and it is the wrong tool for an age gate, a legal check or anything where being off by one day changes the answer. Use Method 1 or Method 2 for those. If you want a fractional age instead of whole years, decimal age is the cleaner display — 36.5 rather than 36 years and 6 months.

Method 4: A Working Form Example

If you need to know how to calculate age in JavaScript inside a form, this is the version to copy. The date input gives you an ISO string such as “1990-05-15”, the `max` attribute blocks future dates, and the script checks the 18+ rule before the form can be submitted.

<form id="ageForm">
  <label for="dateOfBirth">Date of birth:</label>
  <input type="date" id="dateOfBirth" name="dob" required max="2008-11-15">
  <button type="submit">Check my age</button>
  <p id="result"></p>
</form>

<script>
  document.getElementById('ageForm').addEventListener('submit', (e) => {
    e.preventDefault();
    const dobInput = document.getElementById('dateOfBirth').value; // "1990-05-15"
    if (!dobInput) return;
    const parts = dobInput.split('-').map(Number);
    const birthDate = new Date(parts[0], parts[1] - 1, parts[2]);
    const age = calculateAge(birthDate);
    document.getElementById('result').textContent =
      age >= 18 ? `Age: ${age} years old — eligible.` : `Age: ${age} — you must be 18.`;
  });
</script>

Two details in this example matter. First, the `max` value of 2008-11-15 means nobody born after 15 November 2008 — nobody under 18 on the day this article was written — can even pick a date. Second, the month is built with `parts[1] – 1`, because JavaScript months are 0-indexed. This is the trap that catches most beginners: `new Date(2000, 2, 5)` is not 5 February 2000, it is 5 March 2000 — verified by running it, since month index 2 is March. If you pass the month straight from a form or a spreadsheet without subtracting 1, every age you calculate will be a month out. The same birthday rule works in a spreadsheet — our Google Sheets guide shows the DATEDIF version of it.

The February 29 Problem

The trickiest part of how to calculate age in JavaScript is the 29 February birthday. JavaScript itself does not help: in a non-leap year it rolls the date forward, so `new Date(2000, 1, 29)` followed by `setFullYear(2026)` gives Sunday 1 March 2026, not 28 February. That is a real run output, not a guess. Our site’s rule — the one the age calculator on the homepage uses — is that a leap-day birthday is celebrated on 28 February in non-leap years, which is also the rule in England and Wales. If your code follows the JavaScript rollover instead, a leapling will appear to turn a year older on 1 March, a day late by our rule, and an age gate on 28 February will give the wrong answer for that one day. Handle it explicitly:

function birthdayThisYear(birthDate, year) {
  const isLeapYear = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  if (birthDate.getMonth() === 1 && birthDate.getDate() === 29 && !isLeapYear) {
    return new Date(year, 1, 28); // 28 February in non-leap years
  }
  return new Date(year, birthDate.getMonth(), birthDate.getDate());
}

With that rule, someone born on 29 February 2000 is 26 on 15 November 2026 and was still 25 on 15 February 2026 — both verified above. If your product serves users in a jurisdiction that uses 1 March instead, change the 28 to a 1 March date and document the choice; the important thing is to choose deliberately rather than inheriting JavaScript’s silent rollover.

The Timezone Trap in Date Strings

The last silent bug in how to calculate age in JavaScript is parsing. `new Date(‘1990-05-15’)` looks harmless, but a date-only string is parsed as midnight UTC, not midnight local time — so in New York it represents 8 p.m. on 14 May, and a strict day comparison can come out a day early. MDN’s Date reference documents this directly: date-only forms are interpreted as UTC, while date-time forms are interpreted as local time. The form example above avoids the trap by splitting the string and building the date from parts in local time. The alternative is to be consistent: use the UTC getters (`getUTCFullYear`, `getUTCMonth`, `getUTCDate`) everywhere, and never mix them with the local-time getters in the same calculation. Pick one timezone basis and keep it for the whole function.

Libraries and the Temporal API

If you would rather not hand-roll how to calculate age in JavaScript, a date library removes most of these traps. The date-fns function `differenceInYears` does the birthday-aware comparison for you, and Luxon’s `diff` with `[‘years’, ‘months’, ‘days’]` returns the detailed breakdown — both named here as plain text, not links, because the native methods above cover the same ground for a single calculation. The Temporal API is the future standard for this work, but do not write code that depends on it yet without checking support: on Node.js v24.22.1, `typeof Temporal` is `undefined`, so the global is not available in that runtime without a polyfill. In the browser it is shipping in recent Chrome and Firefox releases, and the `@js-temporal/polyfill` package covers the rest. If your code must run in Node today, the Date methods in this guide are the portable choice.

What the Top Guides Get Wrong

The guides that currently rank for how to calculate age in JavaScript are weaker than they look. Four of the top five results are near-identical pages from copyprogramming.com, a content-farm pattern that repeats the same snippets across different URLs. Its timestamp method divides by 365.25, which this guide shows can be off by one; its February 29 note says leaplings turn a year older on 1 March, against our site’s 28 February rule; and none of its pages shows a verified run output for any snippet. The remaining established guide, from thelinuxcode.com, is more than three years old and predates the current best practice around Temporal and form validation. What this article adds is simple: every snippet above was run on Node.js v24.22.1 on 15 November 2026, and the outputs printed next to the code are the outputs the code actually produced.

Conclusion

If you only remember one thing about how to calculate age in JavaScript, make it the birthday rule: subtract the years, then subtract 1 if the birthday has not happened yet this year. Method 1 does that in whole years, Method 2 extends it to years, months and days, Method 4 wires it into a form, and Method 3 — the timestamp division — is the one to leave alone for anything that matters. Remember the two traps: months are 0-indexed, so March is month 2, and a 29 February birthday rolls to 1 March in JavaScript unless you handle it yourself. With those handled, the function at the top of this guide will give the right age on every date you throw at it.

Frequently Asked Questions

What is the simplest way to calculate age in JavaScript?

Subtract the birth year from the current year, then subtract 1 if the birthday has not happened yet this year. The `calculateAge` function at the top of this guide does exactly that, and it is the simplest reliable way to learn how to calculate age in JavaScript.

Why does new Date(2000, 2, 5) give 5 March 2000?

Because JavaScript months are 0-indexed: January is 0, February is 1 and March is 2. So month index 2 is March, not February. Always subtract 1 from a human month number when you build a date from parts.

How do you calculate age in JavaScript for a 29 February birthday?

Decide the rule first: the short answer to how to calculate age in JavaScript for a 29 February birthday is that you must pick a rule before you write the code. This site uses 28 February in non-leap years; JavaScript itself rolls the date to 1 March. Use the `birthdayThisYear` helper in this guide to apply the 28 February rule, and verify the result: born 29 February 2000 is 26 on 15 November 2026.

Is dividing by 365.25 an accurate way to calculate age?

No. It gives a fractional age that is usually right after flooring, but the 365.25 divisor is an average, not a calendar rule, so it can be off by one day near a birthday. Use the calendar comparison in Method 1 for any age that matters.

Does new Date(‘1990-05-15’) use local time?

No. A date-only string is parsed as midnight UTC, so in timezones behind UTC it represents the evening of 14 May. Split the string and build the date from parts, or use the UTC getters consistently.

Can I use the Temporal API to calculate age in JavaScript?

In recent browsers, yes — Temporal is shipping in current Chrome and Firefox. In Node.js v24.22.1 the global is not available (`typeof Temporal` is `undefined`), so use the `@js-temporal/polyfill` package or stick with the Date methods in this guide until your runtime supports it.

Leave a Reply

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