Simple Age Calculator in HTML & JavaScript

Sometimes, we need to calculate the age of users from their date of birth for various purposes. Whether you want to display the age of a user on a profile page or want to validate a user registration form for a specific age condition, you need to determine the age. So, how you can determine the age of a user? Well In this tutorial, we are going to develop a simple age calculator application in HTML and JavaScript.

The basic requirement of this program is that it will get the date of birth in dd/mm/yyyy format and display the age in years, months, and days. The program must check some conditions during the calculation process. Like, determining the correct format of entered date of birth, convert values from string to number, etc.

So, before getting started with coding, you must clear the concept of what we are going to do. In the very first step, we need to create a basic HTML structure in which we’ll get the date of birth and show the output in a div element. After that, we’ll specify some basic CSS styles for the app and finally add the JavaScript program in which we do the following:

  1. Declare input events
  2. Check input is not undefined & correct syntax
  3. Convert value from input(string) to format date dd/mm/yyyy
  4. Call the function to calculate age

OK! now let’s start with HTML to make a simple calculator program.

HTML Code for Age Calculator

The HTML code is really simple, we just need two elements input and span tag for output. Further, you can wrap these elements in div tags to style better. So, create the HTML for the age calculator as follows:

<div class='indent-20'>
      Enter your date of birth:  
      <input id="dob" type="text" placeholder="dd/mm/yyyy"> (ex: dd/mm/YYYY)
      Your age: <span id="age"></span>

Basic CSS Styles

The "indent-20" class is the main container for the age calculator. Define its 640px max-width property along with margin 10px auto to align it to the center. You can further define CSS properties in order to customize it.

.indent-20 {
  margin: 10px auto;
  max-width: 640px;

After that, target the input element and set its height, margin, border, and max-width property as described below:

.indent-20 input {
  height: 30px;
  margin: 0 5px;
  border: 1px solid #909090;
  padding: 0 10px;
  outline: 0;
  max-width: 320px;

Now, target the input with hover and focus pseudo-selectors and define the border color and box-shadow.

.indent-20 input:hover, .indent-20 input:focus {
  border-color: #44b2f8;
  box-shadow: 0px 0px 4px #44b2f8;

The "wrong" class will be added to the input element in case of an invalid DOB entry. Define the red background with a white font size for the error.

.indent-20 #age.wrong {
  background-color: red;
  color: #fff;

Define the CSS styles for the span element that shows the calculated age. The "success" class added dynamically after age calculation. So, you can style the output container differently (before & after output).

.indent-20 #age {
  padding: 5px;
.indent-20 #age.success {
  background-color: #44b2f8;
  color: #fff;

JavaScript Program to Calculate Age

Finally, add the following age calculator program (between the <script></script> tag) into your project and done.

  // Declare global variable
  var elem = document.getElementById('dob'),
      age  = document.getElementById('age');
  // Step to step
  // Step 01: declare input events (change)
  elem.addEventListener("change", function(){
    if (checkInput(elem.value)){
      var ageCount = calculateAge(parseDate(elem.value), new Date()); = '#44b2f8'; = '0px 0px 4px green';
      age.innerHTML = ageCount[0] + ' years old and ' + ageCount[1] + ' days';
    } else { = 'red'; = '0px 0px 4px red';
      age.innerHTML = 'Please enter the correct syntax';
  }, false);
  // Step 02: Check input is not undifined & correct syntax
  function checkInput(textDate){
    var getTextDate = textDate;
    if(getTextDate == '') {
      // If input when change is empty => result return true (NaN)
      return true;
    } else {
      // Declare regular expression 
      var regularDate = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
      // Search regular expression and return Array
      // it's return every elem ( ex: 27/12/1992 => array [27/12/1992,27,/,12,/,1992] )
      var matchArray = getTextDate.match(regularDate); // is format OK?
      if (matchArray == null) {
        // When input center is Alpha return false -Please enter the correct syntax-
        return false;
      } else {
        // Checks for dd/mm/yyyy format.
        var matchDay = matchArray[1];
        var matchMonth = matchArray[3];
        var matchYear = matchArray[5];
        // Check input year large year now3
        if(new Date(matchYear).getFullYear() >= new Date().getFullYear()) {
          return false;
        if (matchDay > 31 || matchDay < 1) {
          return false;
        } else if (matchMonth > 12 || matchMonth < 1) {
          return false;
        } else if ((matchMonth == 2 || matchMonth == 4 || matchMonth == 6 || matchMonth == 9 || matchMonth == 11) && matchDay == 31) {
          return false;
        } else if (matchMonth == 2) {
          var isleap = (matchYear % 4 == 0 && (matchYear % 100 != 0 || matchYear % 400 == 0));
          if (matchDay > 29 || (matchDay == 29 && !isleap)) {
           return false; 
          } else {}
    return true; 
  // Step 03: convert value from input(string) to format date dd/mm/yyyy
  function parseDate(stringText){
    var formatText = stringText.split('/');
    return new Date(formatText[2], (formatText[1] - 1), formatText[0]);
  // Step 04: call function calculate (result how old years & date)
  function calculateAge(DateFromInput, DateNow){
    var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
    var age = Math.round(Math.abs((DateFromInput.getTime() - DateNow.getTime())/(oneDay)));
    var resultYear = Math.ceil(age / 365) - 1;
    var resultDay = age - (resultYear*365);
    var resultage = [];
    resultage.push(resultYear, resultDay);
    return resultage;

That’s all! I hope you have successfully implemented age calculator code into your project. If you have any questions or need further help, let me know by comment below.

You May Also Like

Leave a Comment