How to calculate age by date of birth in JavaScript

Write a Javascript program to calculate age using the text box and show the result in an alert box In this Javascript Exercise, We will some examples to find the age from date of birth in different scenarios Like.

  • Calculate age in JS.
  • Calculate age in days javascript.
  • Javascript validate age < 18.
  • Calculate age from date of birth in javascript using the date picker.
  • Calculate age in years, months, and days javascript.

Calculate age in Javascript

In this, we will learn how to calculate age in javascript using the date and time function. Using these functions we can easily find the age of users from their date of birth for this we take input from users and the current system date.

Algorithm to Calculate Age using Javascript

  • var dob = new Date(“06/24/2008”);  
  • Calculate month difference from the current date in time  
  • Convert the calculated difference in date format
  • Extract year from date
  • Now, calculate the age of the user.
  • At last, display the calculated age.

Java Script Code to calculate Age

<html>
<head>
  <title>Age calculator</title>
<script>
function ageCalculator() {
    var userinput = document.getElementById("DOB").value;
    var dob = new Date(userinput);
    if(userinput==null || userinput=='') {
      document.getElementById("message").innerHTML = "**Choose a date please!";  
      return false; 
    } else {
    var month_diff = Date.now() - dob.getTime();
    var age_dt = new Date(month_diff); 
    var year = age_dt.getUTCFullYear();
    var age = Math.abs(year - 1970);
    alert(document.getElementById("result").innerHTML =  
             "Age is: " + age + " years. ")
    }
}
</script>
</head>
<body>
<center>
<h2 style="color: 32A80F" align="center"> Calculate Age from Date of Birth <br> <br> </h2> 
<b> Enter Date of Birth: <input type=date id = DOB> </b>
<span id = "message" style="color:red"> </span> <br><br>  
<button type="submit" onclick = "ageCalculator()"> Calculate age </button> <br><br>
<h3 style="color:32A80F" id="result" align="center"></h3> 
</center>
</body>
</html>

Output

In this way, we learned to Write a Javascript program to calculate age using the text box and show the result in an alert box.

Calculate age in days javascript

In this, there are date and time functions, which help to calculate the age from the user’s input ie date of birth. Using this we can easily find the age of the user. For this, we require a date input from the user and the current date to calculate the age.

There are some conditions the current date is less than the birthdate entered by the user, the current year will not be counted we will subtract by adding the total number of months to the current month.

Steps

  • Initialize var dob
  • Calculate month difference from current date in time using var month_diff = Date.now() – dob.getTime()
  • Convert the calculated difference in date format using var age_dt = new Date(month_diff)
  • Extract year from date using var year = age_dt.getUTCFullYear()
  • Now calculate the age of the user using var age = Math.abs(year – 1970)
  • Display the calculated age use document.write(“Age of the date entered: ” + age + ” years”);

program to calculate age in days in JS

<!DOCTYPE html>
  <head>
    <title>Age in days </title>
  </head>
  <body>
    <center>
      <h1> how many days old you are:</h1>
      <div class="date-input">
        <input id="day" placeholder="Day" />
        <input id="month" placeholder="Month" />
        <input id="year" placeholder="Year" />
      </div>
      <div class="actionBtns">
        <button class="findOut" onclick="yourAgeInDays()">Find out!</button>
      </div>

      <div id="calculated">
        <h1 id="result"></h1>
      </div>
      <div>
        <p class="millisecondsCount" id="nrms"></p>
      </div>
    </center>

    <style>
      * {
        margin: 0;
        padding: 0;
        font-family: "Short Stack", cursive;
        background: #151f1c;
      }

      h1
      {
        margin-top: 50px;
        letter-spacing: 3px;
        font-weight: bold;
        color: #fee6ff;
      }

      .date-input {
        padding: 20px;
        display: flex;
        justify-content: space-around;
        flex-direction: row;
        flex-wrap: wrap;
      }

      input {
        max-width: 150px;
        padding: 10px;
        outline: none;
        text-align: center;
        font-size: 20px;
        border-radius: 40px;
        border: 5px double #182420;
        color: #fee6ff;
      }

      input:hover {
        background: #263832;
      }

      .actionBtns {
        margin-right: 250px;
        margin-left: 250px;
        padding: 10px;
        display: flex;
        justify-content: space-around;
        flex-direction: row;
        flex-wrap: wrap;
      }

      .findOut
       {
        width: 160px;
        height: 67px;
        outline: none;
        text-align: center;
        letter-spacing: 1px;
        font-size: 25px;
        border-radius: 40px;
        border: 5px solid #182420;
        color: #fee6ff;
      }

      .findOut:hover,
      {
        background: #263832;
      }

      .calculated {
        padding: 20px;
        display: flex;
        justify-content: space-around;
        align-items: center;
        flex-direction: row;
        flex-wrap: wrap;
        letter-spacing: 2px;
      }

      

      #nrms {
        color: #423a3a;
      }
    </style>
    <script>
      "use strict";

      const ageTwenty = 7300;
      const ageJeanne = 44695;

      function yourAgeInDays() {
        let currentDate = new Date();

        let day = document.querySelector("#day").value;
        let month = document.querySelector("#month").value;
        let year = document.querySelector("#year").value;

        let dateOfBirth = new Date(year + "-" + month + "-" + day);

        let difference = Math.abs(currentDate - dateOfBirth);
        let result = Math.round(difference / (1000 * 3600 * 24));

        if (day === "" || month === "" || year === "") {
          document.getElementById("result").innerHTML =
            "Please type your full date of birth.";
        } else if (dateOfBirth > currentDate) {
          document.getElementById("result").innerHTML = "You're not yet born!?";
        } else if (isNaN(result) || isNaN(day) || isNaN(month) || isNaN(year)) {
          document.getElementById("result").innerHTML =
            "Type a proper date";
        } else {
          if (result < ageTwenty) {
            let textAnswer =
              "You are " + result.toString() + " days old";
            document.getElementById("result").innerHTML = textAnswer;
          } else if (result >= ageTwenty && result < ageJeanne) {
            let textAnswer = "You are " + result.toString() + " days old";
            document.getElementById("result").innerHTML = textAnswer;
          } else {
            document.getElementById("result").innerHTML = "Value ERROR!!!";
            setTimeout(function () {
              document.getElementById("result").innerHTML =
                " let me calculate ...";
            }, 1500);
            setTimeout(function () {
              document.getElementById("result").innerHTML =
                "You are " +
                result.toString() +
                " days old";
            }, 2000);
          }
        }
      }

  
    </script>
  </body>
</html>

Output

In this way, we learned to calculate age in days using js.

Javascript validate age < 18

In these, we have to find or validate that the user is 18 or older from the date of birth. From the user input, we can calculate this user is 18 or older than 18 in javascript.

Steps

  • Use function underAgeValidate()
  • Initialize my birthday using optimized birthday variable
  • initialize current date
  • then and if() condition to return a true or false value
  • use console.log function to get output

Program to validate age<18 in JS

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Age in YYYY-MM-DD </title>
</head>
<body>
<script>
// To calculate age:
function underAgeValidate(birthday){
  var optimizedBirthday = birthday.replace(/-/g, "/");
  var myBirthday = new Date(optimizedBirthday);

  var currentDate = new Date().toJSON().slice(0,10)+' 01:00:00';

  var myAge = ~~((Date.now(currentDate) - myBirthday) / (31557600000));

  if(myAge < 18) {
     	    return false;
        }else{
      return true;
  }

} 

console.log(underAgeValidate('2007-02-7'));  //false 
//console.log(underAgeValidate('1999-08-06'));  //true
</script>
</body>
</html>

Output

In this way, we learned how to validate age less than or greater than 18 using JavaScript.

Calculate age from date of birth in javascript using date picker or calendar

In this, we will learn how to calculate age in javascript by taking input (DOB) from the user chosen from the calendar.

Steps

  • Take input from the user(DOB) using the calendar
  • Calculate month difference from the current date in time
  • Then convert the calculated difference in date format
  • Extract year from date
  • Now calculate the age of the user
  • Display calculated age

program to Calculate age from date of birth in javascript using calendar

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <script>
        function ageCalculator() {
    var userinput = document.getElementById("DOB").value;
    var dob = new Date(userinput);
    if(userinput==null || userinput=='') {
      document.getElementById("message").innerHTML = "**Choose a date please!";  
      return false; 
    } else {
    
    var month_diff = Date.now() - dob.getTime();
    
    var age_dt = new Date(month_diff); 
       
    var year = age_dt.getUTCFullYear();

    var age = Math.abs(year - 1970);
    
    return document.getElementById("result").innerHTML =  
             "Age is: " + age + " years. ";
    }
}
</script>
</body>
<center>
<h2 style="color: #0f32a8" align="center"> Calculate Age from DOB using calender <br> <br> </h2> 

<b> Enter Date of Birth: <input type=date id = DOB> </b>
<span id = "message" style="color:red"> </span> <br><br>  

<button type="submit" onclick = "ageCalculator()"> Calculate age </button> <br><br>
<h3 style="color:32A80F" id="result" align="center"></h3> 
</center>
</html>

Output

In this way, we learned how to calculate age in JS using Calendar.

Calculate age in years, months, and days javascript

In this, we will learn how to calculate age years, months, days in this format in Javascript for this we are calculating the age by converting the dates difference in milliseconds.

Steps

  • First, take the input from the user to convert it into dates format
  • Then execute if the user entered a date else collect the only date from date string
  • Get the current date from the system, calculate the difference of dates
  • DOB is greater than today’s date then display error else display age in the above format

Program to calculate age in years, months, days format in javascript

<html>  
<head>
<title> Age in Years , months , days format </title>  
<script>  
  
function ageCalculator() {    
    var userinput = document.getElementById("DOB").value;  
    var dob = new Date(userinput);  
       
    if(userinput==null || userinput==''){  
      document.getElementById("message").innerHTML = "**Choose a date please!";    
      return false;   
    }   
        
    else {   
    var mdate = userinput.toString();  
    var dobYear = parseInt(mdate.substring(0,4), 10);  
    var dobMonth = parseInt(mdate.substring(5,7), 10);  
    var dobDate = parseInt(mdate.substring(8,10), 10);  
       
    var today = new Date();   
    var birthday = new Date(dobYear, dobMonth-1, dobDate);  
      
    var diffInMillisecond = today.valueOf() - birthday.valueOf();        
    var year_age = Math.floor(diffInMillisecond / 31536000000);  
    var day_age = Math.floor((diffInMillisecond % 31536000000) / 86400000);  
       
    if ((today.getMonth() == birthday.getMonth()) && (today.getDate() == birthday.getDate())) {  
            alert("Happy Birthday!");  
        }  
          
     var month_age = Math.floor(day_age/30);          
     day_ageday_age = day_age % 30;  
          
     var tMnt= (month_age + (year_age*12));  
     var tDays =(tMnt*30) + day_age;  
     if (dob>today) {  
        document.getElementById("result").innerHTML = ("Invalid date input - Please try again!");  
      }  
      else {  
        document.getElementById("result").innerHTML = year_age + " years " + month_age + " months " + day_age + " days"  
      }  
   }  
}  
</script>  
</head>  
<body>  
<center>  
<h2 style="color: #008CBA" align="center"> Calculate Age from Date of Birth <br> <br> </h2>   
  
<b> Enter Date of Birth: <input type=date id = DOB>  </b>  
<span id = "message" style="color:red"> </span> <br><br>    
<button type="submit" onclick = "ageCalculator()"> Calculate age </button> <br><br>  
<h3 style="color:#008CBA" id="result" align="center"></h3>   
</center>  
</body>  
</html>

Output

In this way, We learned to calculate age in years, months, days in javascript.