Age Calculator In JavaScript - Beginner Project


In this tutorial, you will learn to create an age calculator in JavaScript. This is a beginner JavaScript project that will help you understand the language.

The age calculator we are going to create is a simple calculator that will help the user to calculate the age of a person.

The user will enter the date of birth of the person and the calculator will calculate the exact age of the person in years, months and days.

The script of the age calculator used in this tutorial is unique, it uses a different approach to calculate the age of the person. Which gives the exact age of the person in days even for a range of thousands of years.

Here is how our age calculator looks:

age calculator in javascript Test the app

    Table Of Contents

  1. JavaScript Age Calculator
    1. Creating Structure Of Age Calculator
    2. Styling The Age Calculator
    3. Writing JavaScript For Age Calculator
  2. Complete Code Of JavaScript Age Calculator
  3. Conclusion

JavaScript Age Calculator

Let's start creating the age calculator app by creating 3 essential files.

  1. HTML (index.html) - This is the main HTML file of the application.
  2. CSS (style.css) - This file is used to write CSS style rules for the application.
  3. JavaScript (script.js) - It is the main JavaScript file of the application. All the logic of the application will be written in this file.

We will discuss each section mentioned above individually. The main motive is to understand here how the logic is created, so we will discuss the JavaScript part in detail.


1. Creating Structure Of Age Calculator

First, we are going to create an HTML structure for the application. The other two files (style.css and script.js) will be connected to this HTML file.

Create a div element with the class container that will contain all the other elements of the application.

Inside the container, create another <div> element with class age-calculator. It will contain everything related to the age calculator.

<div class="container">
  <div class="calculator">

  </div>
</div>

Within the age-calculate element, create a heading that shows the name of the application, a <div> element for controls and a <div> element for result.

<div class="calculator">
  <h1 class="heading"><i class="fas fa-calculator"></i> Age Calculator</h1>
  <div class="controls">

  </div>
  <div class="result"></div>
</div>

The controls element will contain the controls of the application. It will contain the input fields for date input and the buttons for calculating the age.

The result will be displayed within the result element we created above.

<div class="controls">
  <input type="date" id="date">
  <button id="calculate">Calculate</button>
</div>

Complete HTML code:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
  <link rel="stylesheet" href="./style.css">
  <title>Javascript Age Calculator</title>
</head>

<body>
  <div class="container">
    <div class="age-calculator">
      <h1 class="heading"><i class="fas fa-calculator"></i> Age Calculator</h1>
      <div class="controls">
        <input type="date" id="date">
        <button id="calculate">Calculate</button>
      </div>
      <div class="result"></div>
    </div>
  </div>

  <script src="./script.js"></script>
</body>

</html>

Output:

HTML output javascript age calculator

2. Styling The Age Calculator

Now, we are going to style the age calculator. We will create a CSS file and add CSS rules to it.

/* Age Calculator */
body {
  margin: 0;
  box-sizing: border-box;
  font-family: sans-serif;
}

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  margin: 0 auto;
  background-color: #4a171e;
}

.age-calculator {
  background: #fafafa;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.1);
  background-color: #e2b144;
}

.heading {
  font-size: 2.5rem;
  font-weight: bold;
  text-align: center;
  color: #000000;
}

.controls {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
}

.controls input {
  width: 200px;
  height: 40px;
  border-radius: 5px;
  border: 1px solid #ccc;
  padding: 0 10px;
}

.controls button {
  width: 100px;
  height: 40px;
  border-radius: 5px;
  border: 1px solid #ccc;
  background: #4a171e;
  color: #fff;
  font-weight: bold;
  cursor: pointer;
  border: none;
  margin-left: 5px;
}

.result {
  margin-top: 20px;
  text-align: center;
}

.birthdate {
  font-size: 22px;
}

.age {
  font-weight: bold;
  font-size: 25px;
}

.wishing {
  font-size: 40px;
  color: #4a171e;
  font-weight: bold;
  margin-top: 40px;
}

3. Creating Logic For Age Calculator

To start creating JavaScript code for the age calculator, we will start with selecting the elements we want to work with.

I. Select the necessary element

We will select the input field for date input, the button for calculating the age, and the result element.

// selecting the elements
var date = document.getElementById('date');
var calculate = document.getElementById('calculate');
var result = document.querySelector('.result');

II. Set maximum date to today

the first thing to do is to set the date input field to a maximum date of today. We will use the max attribute to set the maximum date.

We need to do this because the date input field will not allow the user to enter a date in the future because birthdays can be only in the past.

// set maximum date to today
date.max = new Date().toISOString().split('T')[0];

III. Create a function to calculate age

Now, we need to create a function to calculate the age. the function name used here is 'calculateAge'. You can use any name you want.

The function will work in 4 stages: First, it will calculate actual age in years, then in months, and then in days. Then in the final stage, it will display the result.

Calculate Exact Year Gap

Year gaps just can't be calculated by taking the difference between the birth year and today's year. Here is why:

For example, if one is born on the 5th, May 2000 and on next year on the 1st of January 2001 you calculate the age by taking the difference between year i.e (2001 - 2000) and got (age = 1) year. Which is wrong. The current age is close to 7 months.

So to calculate the year gap we must see 2 things:

  1. If the current month is greater than the birth month, then you can calculate the year gap by taking the difference between the current year and the birth year.
  2. If the current month is equal to the birth month, then we need to check the day. If the current day is greater than the birthday, then also you can calculate the year gap by taking the difference between the current year and the birth year.
  3. In any other case we need to take 1 year less.
// calculate exact year gap
var years;
if ( today.getMonth() > birthDate.getMonth() ||
     ( today.getMonth() == birthDate.getMonth() &&
      today.getDate() >= birthDate.getDate()
     )
   ) {
  years = today.getFullYear() - birthDate.getFullYear();
}
else {
  years = today.getFullYear() - birthDate.getFullYear() - 1;
}

Calculate Exact Month Gap

Calculating the month gap is easy. We just need to check if the current date is greater than the birth date or equal to the birth date then you can calculate the month gap by taking the difference between the current month and the birth month.

If not, then we need to take 1 month less.

// calculate exact month gap
var months;
if (today.getDate() >= birthDate.getDate()) {
  months = today.getMonth() - birthDate.getMonth();
}
else if (today.getDate() < birthDate.getDate()) {
  months = today.getMonth() - birthDate.getMonth() - 1;
}
// make month positive
months = months < 0 ? months + 12 : months;

In case we get negative months, we need to make it positive by adding 12 to it.

Calculate Exact Day Gap

Calculating the day gap is bit tricky because days can be distributed over 2 different months. For example, if you were born on the 15th, of May and today is the 5th, of June, then for the days gap, you will have to consider days both in May and days passed in June.

So, you have to check if the current date is greater than the birth date or equal to the birth date then you can calculate the day gap by taking the difference between the current date and birth date.

If not, then subtract today's date from birth date and add it to days in the birth month. i.e today.getDate() - birthDate.getDate() + daysInBirthMonth;

// calculate exact day gap
var days;
var monthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if (today.getDate() >= birthDate.getDate()) {
  days = today.getDate() - birthDate.getDate();
} else {
  days = today.getDate() - birthDate.getDate() + monthDays[birthDate.getMonth()];
}

IV. Show the result

Now, we need to show the result. We will use the innerHTML property to set the result.

You can also wish the user happy birthday by checking if the month and days both are 0.

// show result
result.innerHTML = `<p class="birthdate">You were born on ${birthDate.toDateString()}.</p>`;
result.innerHTML += `<p class="age">You are ${years} years, ${months} months and ${days} days old.</p>`;
if (months == 0 && days == 0) {
  result.innerHTML += `<p class="wishing">Happy Birthday!๐ŸŽ‚๐ŸŽˆ๐ŸŽˆ</p>`;
}

V. Add event listener Enter key and autofocus to date input field

// add event listener to calculate button
calculate.addEventListener('click', calculateAge);

// add event listener to enter key
document.addEventListener('keyup', function(e) {
  if (e.keyCode == 13) {
    calculateAge();
  }
});

// autofocus to date input field
date.focus();

Another less accurate method - One way can be to find the number of milliseconds between the two dates and then convert it to days and then to years. But this method is not accurate. As the age increases, it gives the wrong age in days (while age in months or years could be correct).


Complete Code Of JavaScript Age Calculator

Here is the complete code of JavaScript Age Calculator.

Example

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
  <title>Javascript Age Calculator</title>
  <style>
    body {
      margin: 0;
      box-sizing: border-box;
      font-family: sans-serif;
    }

    .container {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      margin: 0 auto;
      background-color: #4a171e;
    }

    .age-calculator {
      background: #fafafa;
      padding: 20px;
      border-radius: 5px;
      box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.1);
      background-color: #e2b144;
    }

    .heading {
      font-size: 2.5rem;
      font-weight: bold;
      text-align: center;
      color: #000000;
    }

    .controls {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 20px;
    }

    .controls input {
      width: 200px;
      height: 40px;
      border-radius: 5px;
      border: 1px solid #ccc;
      padding: 0 10px;
    }

    .controls button {
      width: 100px;
      height: 40px;
      border-radius: 5px;
      border: 1px solid #ccc;
      background: #4a171e;
      color: #fff;
      font-weight: bold;
      cursor: pointer;
      border: none;
      margin-left: 5px;
    }

    .result {
      margin-top: 20px;
      text-align: center;
    }

    .birthdate {
      font-size: 22px;
    }

    .age {
      font-weight: bold;
      font-size: 25px;
    }

    .wishing {
      font-size: 40px;
      color: #4a171e;
      font-weight: bold;
      margin-top: 40px;
    }
  </style>
</head>

<body>
  <div class="container">
    <div class="age-calculator">
      <h1 class="heading"><i class="fas fa-calculator"></i> Age Calculator</h1>
      <div class="controls">
        <input type="date" id="date">
        <button id="calculate">Calculate</button>
      </div>
      <div class="result"></div>
    </div>
  </div>

  <script>
    // selecting the elements
    var date = document.getElementById('date');
    var calculate = document.getElementById('calculate');
    var result = document.querySelector('.result');

    // set maximum date to today
    date.max = new Date().toISOString().split('T')[0];

    function calculateAge() {
      var today = new Date();
      var birthDate = new Date(date.value);

      // Calculate years
      var years;
      if (today.getMonth() > birthDate.getMonth() || (today.getMonth() == birthDate.getMonth() && today.getDate() >= birthDate.getDate())) {
        years = today.getFullYear() - birthDate.getFullYear();
      }
      else {
        years = today.getFullYear() - birthDate.getFullYear() - 1;
      }

      // Calculate months
      var months;
      if (today.getDate() >= birthDate.getDate()) {
        months = today.getMonth() - birthDate.getMonth();
      }
      else if (today.getDate() < birthDate.getDate()) {
        months = today.getMonth() - birthDate.getMonth() - 1;
      }
      // make month positive
      months = months < 0 ? months + 12 : months;

      // Calculate days
      var days;
      // days of months in a year
      var monthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
      if (today.getDate() >= birthDate.getDate()) {
        days = today.getDate() - birthDate.getDate();
      } else {
        days = today.getDate() - birthDate.getDate() + monthDays[birthDate.getMonth()];
      }

      // Display result
      result.innerHTML = `<p class="birthdate">You were born on ${birthDate.toDateString()}.</p>`;
      result.innerHTML += `<p class="age">You are ${years} years, ${months} months and ${days} days old.</p>`;
      if (months == 0 && days == 0) {
        result.innerHTML += `<p class="wishing">Happy Birthday!๐ŸŽ‚๐ŸŽˆ๐ŸŽˆ</p>`;
      }
    }
    calculate.addEventListener('click', calculateAge);

    // run calculate on enter key
    document.addEventListener('keypress', (e) => {
      if (e.keyCode == 13) {
        calculate.click();
      }
    });
    // onload focus on date input
    date.focus();
  </script>
</body>

</html>

Conclusion

The JavaScript age calculator is a simple and easy to use web application. It is a great way to learn how to use JavaScript and DOM.

II is a beginner level JavaScript project which worth to take a look at. It will teach you about Date object in JavaScript and DOM manipulation.

Also, learn how to create JavaScript Calculator.