DEV Community

Arhan Khan
Arhan Khan

Posted on

Build an Age Calculator App with JavaScript

An age calculator takes a date of birth and tells you the exact age in years, months, and days. It sounds trivial, but dates are one of the trickiest things in programming — months have different lengths, leap years exist, and "how old am I" is not a simple subtraction. That is exactly why it is a great beginner project.

How does it work? You read the birth date from a date input, compare it with today's date, and work out the difference year by year, then month by month, then day by day — borrowing from the previous month when the day has not arrived yet this month.

<h2>Age Calculator</h2>
<label>Date of birth <input type="date" id="dob"></label>
<button id="calc">Calculate Age</button>
<p id="result"></p>
Enter fullscreen mode Exit fullscreen mode
document.getElementById('calc').addEventListener('click', () => {
  const dob = new Date(document.getElementById('dob').value);
  const today = new Date();
  if (isNaN(dob) || dob > today) {
    document.getElementById('result').textContent = 'Please pick a valid past date.';
    return;
  }

  let years = today.getFullYear() - dob.getFullYear();
  let months = today.getMonth() - dob.getMonth();
  let days = today.getDate() - dob.getDate();

  if (days < 0) {
    months -= 1;
    // Days in the previous month
    const prevMonth = new Date(today.getFullYear(), today.getMonth(), 0);
    days += prevMonth.getDate();
  }
  if (months < 0) {
    years -= 1;
    months += 12;
  }

  document.getElementById('result').textContent =
    `You are ${years} years, ${months} months and ${days} days old.`;
});
Enter fullscreen mode Exit fullscreen mode

This app is great for beginners because it teaches you the Date object, input validation, and careful thinking about edge cases. Try the date 29 February on a leap year, or a birthday that is tomorrow — the borrowing logic above is what keeps the answer correct.

When should you build it? Whenever you want a project that looks simple but has real depth. You can extend it later: show the total days lived, the next birthday countdown, or the day of the week you were born.

The limits are worth knowing. JavaScript dates depend on the user's timezone, so the same birth date can give a different day count in different timezones. For a fun personal tool that does not matter; for official age checks, always use the date on the document.

Start today: build the calculator above and try your own date of birth, then try 29 February 2000 and see if the answer still looks right. Getting the edge cases right is the real lesson.

Top comments (0)