DocsHub
JavascriptBeginner

Age Calculator

Build an age calculator that calculates a user's exact age from their date of birth.

Age Calculator

Problem

Build an age calculator where the user picks their date of birth and the app instantly shows their exact age in years, months, and days.

Input:  Date of birth: 2000-03-15  (today is 2024-03-15)
Output: 24 years, 0 months, 0 days

Input:  Date of birth: 2000-01-01
Output: 24 years, 2 months, 14 days

Input:  No date selected
Output: Please select your date of birth

Input:  Future date selected
Output: Date of birth cannot be in the future

Logic

  1. Select the date input and result display elements
  2. Listen for the change event on the date input
  3. Get today's date using new Date()
  4. Parse the selected date using new Date(value)
  5. Validate — empty input or future date
  6. Calculate the difference in years, months, and days
  7. Display the result

Flow

no yes yes no User picks date change event fires Date selected? Show please select message Date in future? Show error message Calculate years Calculate months Calculate days Show result

HTML Structure

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Age Calculator</title>
    <style>
      body {
        font-family: sans-serif;
        max-width: 400px;
        margin: 60px auto;
        padding: 0 20px;
      }

      label {
        display: block;
        margin-bottom: 8px;
        font-weight: 500;
      }

      input[type="date"] {
        width: 100%;
        padding: 10px;
        font-size: 1rem;
        border: 2px solid #ccc;
        border-radius: 8px;
        box-sizing: border-box;
      }

      /* result box shown below the input */
      #result {
        margin-top: 20px;
        padding: 16px;
        border-radius: 8px;
        background: #f5f5f5;
        font-size: 1rem;
        color: #333;
        min-height: 50px;
      }

      /* error state */
      #result.error {
        background: #fff0f0;
        color: red;
      }

      /* success state — big age numbers */
      .age-number {
        font-size: 2rem;
        font-weight: 700;
        color: #111;
      }
    </style>
  </head>
  <body>
    <h1>Age Calculator</h1>

    <label for="dob">Date of Birth</label>

    <!-- date input — lets user pick a date from a calendar -->
    <input type="date" id="dob" />

    <!-- result is displayed here -->
    <div id="result">Select your date of birth above.</div>

    <script src="script.js"></script>
  </body>
</html>

Solution

// Step 1 — select elements
const dobInput = document.querySelector("#dob");
const result = document.querySelector("#result");

// Step 2 — set the max date to today
// prevents the user from selecting a future date in the calendar
const today = new Date();
dobInput.max = today.toISOString().split("T")[0]; // format: "YYYY-MM-DD"

// Step 3 — listen for change event
// 'change' fires when the user picks a date and confirms it
dobInput.addEventListener("change", calculateAge);

function calculateAge() {
  // Step 4 — get the selected date value
  const dobValue = dobInput.value;

  // Step 5 — handle empty input
  if (!dobValue) {
    showError("Please select your date of birth.");
    return;
  }

  // Step 6 — parse the selected date into a Date object
  const dob = new Date(dobValue);
  const now = new Date();

  // Step 7 — validate — check if date is in the future
  if (dob > now) {
    showError("Date of birth cannot be in the future.");
    return;
  }

  // Step 8 — calculate years
  let years = now.getFullYear() - dob.getFullYear();
  let months = now.getMonth() - dob.getMonth();
  let days = now.getDate() - dob.getDate();

  // Step 9 — adjust if day difference is negative
  // example: born on 20th, today is 10th — need to borrow from months
  if (days < 0) {
    months--;
    // get the number of days in the previous month
    const prevMonth = new Date(now.getFullYear(), now.getMonth(), 0);
    days += prevMonth.getDate();
  }

  // Step 10 — adjust if month difference is negative
  // example: born in October, current month is March — need to borrow from years
  if (months < 0) {
    years--;
    months += 12;
  }

  // Step 11 — display the result
  result.classList.remove("error");
  result.innerHTML = `
    <span class="age-number">${years}</span> years,
    <span class="age-number">${months}</span> months,
    <span class="age-number">${days}</span> days
  `;
}

// helper function — shows an error message
function showError(message) {
  result.classList.add("error");
  result.textContent = message;
}

Code Execution

Trace through selecting 2000-03-15 (today is 2024-03-15):

StepCodeResult
Parse DOBnew Date("2000-03-15")March 15 2000
Years2024 - 200024
Months2 - 2 (March - March)0
Days15 - 150
Adjustments needednone
Output24 years, 0 months, 0 days

Trace through selecting 2000-05-20 (today is 2024-03-15):

StepCodeResult
Years2024 - 200024
Months2 - 4 (March=2, May=4)-2
Days15 - 20-5
Days < 0borrow from months — days in Feb 2024 = 29days = -5 + 29 = 24, months = -3
Months < 0borrow from yearsyears = 23, months = -3 + 12 = 9
Output23 years, 9 months, 24 days

Output

DOB: 2000-03-15 (today is 2024-03-15) → 24 years, 0 months, 0 days
DOB: 2000-05-20 (today is 2024-03-15) → 23 years, 9 months, 24 days
No date selected                       → Select your date of birth above.
Future date selected                   → Date of birth cannot be in the future.

On this page