DEV Community

mr m
mr m

Posted on

Build a Chronological Age Calculator Using JavaScript (Beginner Friendly)

Calculating age might seem simple, but when you break it down into years, months, and days, it becomes a great beginner project to practice JavaScript.

In this tutorial, we’ll build a chronological age calculator step by step.

🧠 What is a Chronological Age Calculator?

A chronological age calculator is a tool that calculates the exact age of a person based on their date of birth.

It returns:

Years
Months
Days
βš™οΈ Step 1: Get User Input

First, we need to get the user's date of birth:


Calculate

πŸ’» Step 2: JavaScript Logic

Now let’s write the function:

function calculateAge() {
const input = document.getElementById("birthdate").value;
const birthDate = new Date(input);
const today = new Date();

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

if (days < 0) {
months--;
days += 30;
}

if (months < 0) {
years--;
months += 12;
}

document.getElementById("result").innerText =
${years} years, ${months} months, ${days} days;
}

πŸš€ Live Example

If you want to see a complete working version, check this tool:

πŸ‘‰ https://chronologicalage.site/

πŸ’‘ What You Learn
Working with JavaScript Dates
Handling edge cases (months, days)
Building a real-world mini project
βœ… Conclusion

Building a chronological age calculator is a simple but practical project that helps you understand date manipulation javascript.

Top comments (0)