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'>
   <p>
      Enter your date of birth:  
      <input id="dob" type="text" placeholder="dd/mm/yyyy"> (ex: dd/mm/YYYY)
   </p>
   <p>
      Your age: <span id="age"></span>
   </p>
</div>

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.

(function(){
  // 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());
      elem.style.borderColor = '#44b2f8';
      elem.style.boxShadow = '0px 0px 4px green';
      age.innerHTML = ageCount[0] + ' years old and ' + ageCount[1] + ' days';
      age.classList.remove('wrong');
      age.classList.add('success');
    } else {
      elem.style.borderColor = 'red';
      elem.style.boxShadow = '0px 0px 4px red';
      age.innerHTML = 'Please enter the correct syntax';
      age.classList.remove('success');
      age.classList.add('wrong');
    } 
  }, 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 Might Be Interested In:

Muhammad Asif is a Front End Developer and Editor Staff at Codeconvey.com. He enjoys experimenting with new CSS features and helping others learn about them.

9 thoughts on “Simple Age Calculator in HTML & JavaScript”

  1. Sir,
    where should I put the JavaScript Program to Calculate Age, I am using WordPress with Astra theme, I am using contact form 7 in which I need to display the current Age from DOB input.

    • Hi Vineet!
      You can place JavaScript code inside the theme footer. Go to Appearance > Theme Editor > Theme Footer (footer.php) and then place the age calculator code between the script tag.

      Similarly, you can also upload the JavaScript code to your server, and enqueue it using WordPress wp_enqueue_script() function. To do so, go to cPanel > File Manager > public_html > create a new folder, name it “js”. After that create a file inside that folder with name "age-calculator.js", edit it, paste the age calculation function inside it, and save it.
      After that, go to the theme editor in the admin dashboard and select function.php, enqueue the script as follows:

      function include_age_calculator() {
      	wp_enqueue_script('age-calculator', 'https://yourdomain.com/js/age-calculator.js', array(), null, true);
      }
      add_action('wp_enqueue_scripts', 'include_age_calculator');
      

      Copy the above function, update the yourdomain according to your site domain and paste it at the end of function.php file.

  2. Thanks for your support, it is working fine now, but another issue is the date format, my datepicker in contact form 7 allows only dd-mm-yyyy not dd/mm/yyyy, how to change the date format from / (slash) to – (dash), please share the tip.

    • You can change the regular expression in the age calculator function to validate date in your desired format:
      For dd-mm-yyyy format use the following expression:

       // Declare regular expression 
            var regularDate = /^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$/;
      

      You can read more about dates format regular expressions from here: https://www.regular-expressions.info/dates.html

  3. Applicant’s Date Of Birth * (ex: dd-mm-yyyy)
    [date* app_dob]

    i am using date where as you are using text format, how to change, however i have changed the string setting from “/” to “-“, but is not working

  4. Sir,
    Thanks for your support, it is working file as per the text dob format, but it is not working with date dob format in cf7, how to change the text format to date format the code is
    [date* dob] not [text* dob], please share the tip.

    Thanks,

  5. Sir, how to store the age (years and days) for mail tag in cf7, i mean i have to provide conditional fields for different age i.e. if age if > 5 year then do this and if age<5 do this.

    • This is an HTML and Javascript version so you need to modify it according to CF7.

Comments are closed.