Age calculator HTML Code for website

html calculation javascript calculation 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.

If you are curious about the date widget, it is a great one. Here is the code configures the date widget

var picker = new Pikaday({ 
  field: document.getElementById('birth_date') ,
  onSelect: function(date) {
  let age = calculateAge(date);
  document.getElementById('age').innerHTML = "age: "+age ;

The onSelect callback function gets triggered when the user selects a date from the widget.

You can use any datepicker widget as long as you can get the selected date from the widget when a date is selected.

See Also