Age Calculator Using JavaScript

Table of Contents

Technologies used -
Description

The Age Calculator is a simple yet effective web application that allows users to determine their age in years, months, and days based on their birth date. This tool utilizes a user-friendly interface, enabling individuals to input their birth date via a date picker and receive an instant calculation of their age. With an emphasis on clarity and ease of use, this calculator provides an engaging experience for users while learning or testing JavaScript functionalities.

The application is designed to accommodate real-time input, ensuring users can only select valid dates up to the current day. When the “Calculate” button is clicked, the script processes the input and calculates the difference between the user’s birth date and today’s date, breaking it down into years, months, and days. This approach not only demonstrates fundamental JavaScript concepts but also showcases how to manipulate date objects effectively.

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 is a classic two-player game implemented using HTML, CSS, and JavaScript. This engaging application

Read More »