Javascript calculate age: Here is this tutorial we are going to learn how we can calculate age from the given Date of Birth (DOB) in javascript. I have a requirement where I have to calculate the user's age based on its DOB. To check user age eligibility and apply respective validation.
For example on the registration page if the user's age is less than 18, then we add validation by which user can't create an account. So based on DOB I can disable or enable the submit button respectively.
2 ways to calculate age in Javascript
- Calculate age from date of birth to current date.
- Calculate the age between the given two dates.
Calculate age from date of birth to current date
Here in this method, we add an input textbox and button tag. On button click, we call javascript function which gets the date from the input textbox and calculates age.
Our HTML code looks like as below:
<input type="date" id="txtDOB" />
<button id="btnCalculate" onclick="fnCalculateAge();" >Calculate Age</button>
Here's to calculate age from date of birth JavaScript function is as follow:
function fnCalculateAge(){
var userDateinput = document.getElementById("txtDOB").value;
console.log(userDateinput);
// convert user input value into date object
var birthDate = new Date(userDateinput);
console.log(" birthDate"+ birthDate);
// get difference from current date;
var difference=Date.now() - birthDate.getTime();
var ageDate = new Date(difference);
var calculatedAge= Math.abs(ageDate.getUTCFullYear() - 1970);
alert(calculatedAge);
}
# Calculate the age between given two date.
Here we going to add two textboxes i.e start date and end date. On button click, we call js function fnCalculateAgeFromGivesDates.
Our HTML markup looks like as written below:
<input type="date" id="txtStartDate" />
<input type="date" id="txtEndDate" />
<button id="btnCalculate2" onclick="fnCalculateAgeFromGivesDates();" >Calculate Age</button>
JS code to calculate age from two dates is as follow:
function fnCalculateAgeFromGivesDates(){
var startDateInput = document.getElementById("txtStartDate").value;
var endDateInput = document.getElementById("txtEndDate").value;
// convert user input values into date object
var startDate = new Date(startDateInput);
var endDate = new Date(endDateInput);
// get difference between two date;
var difference=endDate - startDate.getTime();
var ageDate = new Date(difference);
var calculatedAge= Math.abs(ageDate.getUTCFullYear() - 1970);
alert(calculatedAge);
}
Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.
PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee
Post Comment
Your email address will not be published. Required fields are marked *