How to Calculate Age in JavaScript (Date Object and Day.js Examples)
Learn how to calculate age from date of birth in JavaScript: a plain Date solution, a safer approach for time zones, and Day.js examples you can copy-paste.
How to Calculate Age in JavaScript (Date Object and Day.js Examples)
Age looks simple until you hit edge cases: time zones, birthdays that have not happened yet this year, and different input formats. Below are compact JavaScript patterns for the most common definition of age: completed years.
Fast option: use an online age calculator
If you need an exact breakdown in years, months, and days, or you want a quick answer for arbitrary dates, use a tool and then port the logic into code.
Open the age calculator and enter date of birth plus the reference date (today or any date).
Age in full years (plain JavaScript)
This returns the number of completed years as of a given date.
function ageYears(dob, asOf = new Date()) {
const birth = new Date(dob);
let years = asOf.getFullYear() - birth.getFullYear();
const m = asOf.getMonth() - birth.getMonth();
if (m < 0 || (m === 0 && asOf.getDate() < birth.getDate())) years--;
return years;
}
ageYears('1998-10-12');
Tip: avoid time zone surprises
If you parse YYYY-MM-DD with new Date('2020-01-01'), it is treated as UTC by many runtimes, which can shift the local date. A simple fix is to parse into a local date.
function parseLocalDate(yyyyMmDd) {
const [y, m, d] = yyyyMmDd.split('-').map(Number);
return new Date(y, m - 1, d);
}
ageYears(parseLocalDate('1998-10-12'));
Using Day.js (with plugins)
Day.js can make parsing and comparisons cleaner. You typically want the customParseFormat plugin if you accept multiple input formats.
// npm i dayjs
// dayjs.extend(customParseFormat)
function ageYearsDayjs(dobStr, asOfStr) {
const dob = dayjs(dobStr, 'YYYY-MM-DD', true);
const asOf = asOfStr ? dayjs(asOfStr, 'YYYY-MM-DD', true) : dayjs();
let years = asOf.year() - dob.year();
const hadBirthday = asOf.month() > dob.month() || (asOf.month() === dob.month() && asOf.date() >= dob.date());
if (!hadBirthday) years--;
return years;
}
FAQ
What is the correct definition of age in years?
In most apps it is the number of completed years (you turn 30 on your birthday, not earlier). That is what the examples above calculate.
How do I calculate exact age (years, months, days)?
You can compute it by subtracting units carefully, but it is easy to get wrong around month lengths and leap years. A dedicated calculator is a good baseline for tests.