
How to calculate age from date of birth?

<html>
<head>
<script type="text/javascript">
function ageCount() {
var date1 = new Date();
var dob= document.getElementById("dob").value;
var date2=new Date(dob);
var pattern = /^\d{1,2}\/\d{1,2}\/\d{4}$/; //Regex to validate date format (dd/mm/yyyy)
if (pattern.test(dob)) {
var y1 = date1.getFullYear(); //getting current year
var y2 = date2.getFullYear(); //getting dob year
var age = y1 - y2; //calculating age
document.write("Age : " + age);
return true;
} else {
alert("Invalid date format. Please Input in (dd/mm/yyyy) format!");
return false;
}
}
</script>
</head>
<body>
Date of Birth(dd/mm/yyyy):
<input type="text" name="dob" id="dob" />
<input type="submit" value="Age" onclick="ageCount();">
</body>
</html>
Description: Here you can use regular expression to validate date format. If inputted date of birth is in form of dd/mm/yyyy then count age by subtracting dob into current date. you can also take specified date in place of current date to count age. getFullYear() is used here to get year of specified date.
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.