JAVASCRIPT PROJECT 03

Build an Age Calculator

In this project, you will learn how to create an Age Calculator using HTML, CSS and JavaScript. The user will enter a date of birth and JavaScript will calculate the age in years, months and days.

01

Project Introduction

An Age Calculator takes a person's date of birth and compares it with today's date. The difference between these two dates gives us the person's age.

What You Will Learn

  • HTML date input
  • JavaScript Date object
  • getFullYear()
  • getMonth()
  • getDate()
  • Date comparison
  • DOM manipulation
  • Form validation
Input User selects date of birth.
JavaScript Calculates the difference.
Output Age is displayed on screen.
02

Create the HTML Structure

First, create a container for the Age Calculator. We need a heading, date input, button and result area.

<div class="age-calculator">

    <h2>
        Age Calculator
    </h2>

    <input type="date" id="dob">

    <button onclick="calculateAge()">
        Calculate Age
    </button>

    <div id="result"></div>

</div>
The input collects the date of birth, while the result element will display the calculated age.
03

Create the Date Input

HTML provides a special input type called date. It gives the user a date picker.

<label>
    Date of Birth
</label>

<input
    type="date"
    id="dob"
>

Why use type="date"?

It allows the user to select a valid date without manually typing the complete date format.

04

Create a JavaScript Date Object

JavaScript has a built-in Date object for working with dates and times.

const today = new Date();

We can also create a Date object from the user's date of birth.

const birthDate =
    new Date(dobInput.value);
The Date object allows JavaScript to compare and calculate dates.
05

Get Today's Date

To calculate someone's age, we need the current date.

const today = new Date();

console.log(today);

JavaScript automatically gets the current date and time from the user's device.

06

Calculate the Years

We can get the year from both dates and subtract the birth year from the current year.

let years =
    today.getFullYear()
    -
    birthDate.getFullYear();

Example

2026 - 2000 = 26
This gives the basic age. We still need to adjust the result depending on the month and day.
07

Calculate the Months

JavaScript's getMonth() returns the month number. January is 0 and December is 11.

let months =
    today.getMonth()
    -
    birthDate.getMonth();

If the current month is earlier than the birth month, we need to reduce the calculated year by one.

if(months < 0){

    years--;

    months += 12;

}
08

Calculate the Days

Now compare the current day with the birth day.

let days =
    today.getDate()
    -
    birthDate.getDate();

Handle Negative Days

If the current day is smaller than the birth day, we need to borrow days from the previous month.

if(days < 0){

    months--;

    const previousMonth =
        new Date(
            today.getFullYear(),
            today.getMonth(),
            0
        );

    days +=
        previousMonth.getDate();

}
09

Validate the Input

The user might click the button without selecting a date. We should handle that situation.

if(!dobInput.value){

    error.textContent =
        "Please select your date of birth.";

    return;

}

Prevent Future Dates

A person's date of birth cannot be later than today.

if(birthDate > today){

    error.textContent =
        "Date of birth cannot be in the future.";

    return;

}
Validation makes the project safer and provides a better user experience.
10

Display the Result

After calculating the age, use DOM manipulation to show the result on the webpage.

const result =
    document.getElementById("result");

result.textContent =
    years + " Years, "
    + months + " Months, "
    + days + " Days";

Example Result

25 Years, 4 Months, 12 Days
11

Put Everything Inside One Function

All the calculation logic can be placed inside a function called calculateAge().

function calculateAge(){

    const dobInput =
        document.getElementById("dob");

    const birthDate =
        new Date(dobInput.value);

    const today =
        new Date();

    // Calculate years

    // Calculate months

    // Calculate days

    // Display result

}
The button calls calculateAge() when the user clicks "Calculate Age".

Complete Project Flow

INPUT DOB
DATE Date Object
CALCULATE Y/M/D
VALIDATE Check Input
OUTPUT Result
12

Complete Age Calculator

You have now learned how an Age Calculator is built using HTML, CSS and JavaScript. The complete project combines all the concepts explained above.

Tutorial Completed! 🎯

Now open the complete working Age Calculator and test what you have learned.

Run Complete Project Learn JavaScript Date