Age Calculator Using JavaScript

Technologies used -
Description

The Age Calculator is a simple tool that helps users find their age in years, months, and days. First, users select their birth date using a date picker. Then, the calculator instantly shows their age. It is easy to use and clear, offering a smooth experience for anyone learning or testing JavaScript.

Moreover, the app allows users to enter their birth date and ensures they can only select valid dates up to today. When users click “Calculate,” the tool finds the difference between the birth date and today’s date. It then breaks the result down into years, months, and days. This app not only demonstrates basic JavaScript concepts but also shows how to work with date objects.

Highlighted Source Code
				
					let userInput = document.getElementById("date");
userInput.max = new Date().toISOString().split("T")[0];
let result = document.getElementById("result");

function calculateAge() {
    let birthDate = new Date(userInput.value);

    let d1 = birthDate.getDate();
    let m1 = birthDate.getMonth() + 1;
    let y1 = birthDate.getFullYear();

    let today = new Date();
    let d2 = today.getDate();
    let m2 = today.getMonth() + 1;
    let y2 = today.getFullYear();

    let d3, m3, y3;

    y3 = y2 - y1;

    if (m2 >= m1) {
        m3 = m2 - m1;
    } else {
        y3--;
        m3 = 12 + m2 - m1;
    }

    if (d2 >= d1) {
        d3 = d2 - d1;
    } else {
        m3--;
        d3 = getDaysInMonths(y1, m1) + d2 - d1;
    }
    if (m3 < 0) {
        m3 = 11;
        y3--;
    }

    result.innerHTML = `You are <span>${y3}</span> years, <span>${m3}</span> months, and <span>${d3}</span> days old.`;
}

function getDaysInMonths(year, month) {
    return new Date(year, month, 0).getDate();
}
				
			

Related Projects

Fun Project

Tic Tac Toe Game

The Interactive Tic Tac Toe Game lets two players compete in a 3×3 grid. It includes a simple interface, feedback on wins, and sound effects for added fun.

Read More »
Form & Input Handling

Text-to-Speech Converter

This Text-to-Speech app lets you type text and listen to it spoken aloud in different voices. Choose a voice, click ‘Listen,’ and hear the text in real-time.

Read More »