HTML.form.guide

Simplest method - Age Calculator Code for Your website

HTML calculation Javascript calculation age calculation code html age calculation code

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

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

In this function, the age calculation is straightforward; it finds the difference between the dates. The result is in milliseconds. Then we convert it into years.

Here is a live demo of the code. We will use a date picker: pikaday. At the time of this writing, there is still no consistent date input type ( <input type="date" />) that works across browsers. So we have to use a Javascript date widget like pikaday.

Click on the date input field and select a date (click on the year to change the year)

See the Pen Calculate age HTML Code on CodePen.

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 selected date:

<div class="container mt-5">
  <form>
    <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>
    </div>
  </form>
</div>

See a demo here:

See the Pen Calculate age HTML Code

See more calculation forms here

See Also