how to calculate age from date of birth in javascript – Calculate age from date of birth to current date. In our day to day programming we often come across business logic that depends on the age of a person.
how to calculate age from date of birth in javascript
i am going to see how to calculate the age of a person using their birth date as input in JavaScript Example with demo.
calculate age from date of birth in javascript
age calculator javascript
function calculate_age(dob) { var diff_ms = Date.now() - dob.getTime(); var age_dt = new Date(diff_ms); return Math.abs(age_dt.getUTCFullYear() - 1970); } console.log(calculate_age(new Date(1982, 11, 4))); console.log(calculate_age(new Date(1962, 1, 1)));
Calculate age using JavaScript
Example 1: Predefined date input
<script> var dob = new Date("06/24/2001"); 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); document.write("Age of the date entered: " + age + " years"); </script>
Example 2: dynamic date input
index.html
<html> <head> <script> function ageCalculator() { var memberIp = document.getElementById("DOB").value; var dob = new Date(memberIp); if(memberIp==null || memberIp=='') { document.getElementById("message").innerHTML = "**Select 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> </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>
Don’t Miss : Age Date Of Birth Calculation With Counter In Javascript
I hope you get an idea about how to calculate age from date of birth in javascript.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.