DEV Community

Goru Mohd
Goru Mohd

Posted on

How I Built a JavaScript Age Calculator in 2 Hours

The Problem I Faced

A few days ago, I needed to calculate someone's exact age in years, months, and days. I Googled "age calculator" and found:

  • Complicated interfaces
  • Required sign-up
  • Not mobile-friendly

So I decided to build my own.


What I Built

I created calchub-calculators.netlify.app - a free, simple, and clean age calculator.

Features:

Exact age in years, months, and days
Mobile responsive
No sign-up required
100% free forever


How It Works

The calculator takes your birth date as input, compares it with today's date, and gives you:

  • Your exact age in years
  • How many months old you are
  • How many days old you are

How I Built It (Technical Details)

Tech Stack:

  • HTML5 - Structure
  • CSS3 - Styling (clean, minimal design)
  • Vanilla JavaScript - Logic (no frameworks needed)

Key JavaScript Function:


javascript
function calculateAge(birthDate) {
    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 += new Date(today.getFullYear(), today.getMonth(), 0).getDate();
    }

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

    return { years, months, days };
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)