Age Calculator: how it works and how to build one
Exact age in years, months and days, plus next birthday. This guide explains what happens behind the button and shows the code, so you can build your own.
What it does
Enter a date of birth to get the exact age in years, months and days, total days and weeks lived, the day of the week you were born, and a countdown to the next birthday. Change the ‘age on’ date to check age on any date, for example an exam cut-off.
When to use it
- Exam and job age limits
- Birthdays
- Forms that need exact age
How to use it
- Pick the date of birth.
- Optionally change the ‘age on’ date.
- Read the age and next birthday.
Try it free in your browser, nothing is uploaded: https://eskillsfy.com/tools/age-calculator
How it works
Exact age is a date subtraction with borrowing, like subtraction on paper: subtract years, months and days; if days go negative, borrow the number of days in the previous month; if months go negative, borrow 12 months from the years.
Total days uses UTC dates so daylight-saving changes don’t add or remove an hour.
Build it yourself
Here is the core of the tool. It has no dependencies unless noted, so you can paste it into any TypeScript or JavaScript project.
age.ts (ts)
export function age(birth: Date, on = new Date()) {
let y = on.getFullYear() - birth.getFullYear();
let m = on.getMonth() - birth.getMonth();
let d = on.getDate() - birth.getDate();
if (d < 0) { m--; d += new Date(on.getFullYear(), on.getMonth(), 0).getDate(); } // days in previous month
if (m < 0) { y--; m += 12; }
const days = Math.round((Date.UTC(on.getFullYear(), on.getMonth(), on.getDate()) - Date.UTC(birth.getFullYear(), birth.getMonth(), birth.getDate())) / 864e5);
return { years: y, months: m, days: d, totalDays: days };
}
Make it production-ready
- Treat 29 February birthdays as 28 February in other years.
- Add the next-birthday countdown.
Questions
Does it handle leap years?
Yes. Feb 29 birthdays count on Feb 28 in other years.
Free, runs in your browser, nothing is uploaded.