JavaScript Coder

Simple Javascript age calculator code

javascript age calculator javascript calculation

In this tutorial, we will discuss how to create an age calculator using JavaScript. There are two methods that we will explore - the simplest method and a more advanced method using a JavaScript library.

Method 1: Simplest Method - Age Calculator Code for Your Website

Suppose you have a requirement to capture the date of birth of the user and then calculate their age from that date. You can easily do the calculation using the Date JavaScript global object. Here is some sample code that does just that:

function calculateAge(dateOfBirth) 
  const now = new Date();
  const diff = Math.abs(now - dateOfBirth);
  const age = Math.floor(diff / (1000 * 60 * 60 * 24 * 365)); 
  return age;

In this function, the age calculation is straightforward. We find the difference between the current date and the date of birth, and the result is in milliseconds. Then, we convert it into years by dividing it by the number of milliseconds in a year.

To use this function, you can call it with a Date object representing the user’s date of birth, like this:

const age = calculateAge(new Date('1990-01-01')); // replace with user's date of birth
console.log(age); // outputs the user's age in years

Method 2: Even Simpler - Use NittiJS

NittiJS is a JavaScript library that helps you add calculations to your forms. All that you have to do is to provide the calculation formula in the r-calc attribute. Here is a sample form that does age calculation based on the selected date:

<div class="container mt-5">
<div ><label for="birth_date">Birth Date: </label>
  <input type="date" id="birth_date" name="birth_date"/></div>
<div id="age" style="padding-top:2em;">
  Age: <span r-calc="calculateAge(birth_date)" ></span>

In this form, we use the r-calc attribute to calculate the user’s age based on the date of birth that they input.

Here is a demo:

See the Pen Calculate age HTML Code (Using NittiJS)

See Also