Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SH20RAJ/6418bfde2f5db0b1cb0fb493e26decbc to your computer and use it in GitHub Desktop.
Save SH20RAJ/6418bfde2f5db0b1cb0fb493e26decbc to your computer and use it in GitHub Desktop.
Calculate Age from Date of Birth with Birthday alert πŸŽ‚
<html>
<head>
<script>
function ageCalculator() {
//collect input from HTML form and convert into date format
var userinput = document.getElementById("DOB").value;
var dob = new Date(userinput);
//check user provide input or not
if(userinput==null || userinput==''){
document.getElementById("message").innerHTML = "**Choose a date please!";
return false;
}
//execute if user entered a date
else {
//extract and collect only date from date-time string
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);
//get the current date from system
var today = new Date();
//date string after broking
var birthday = new Date(dobYear, dobMonth-1, dobDate);
//calculate the difference of dates
var diffInMillisecond = today.valueOf() - birthday.valueOf();
//convert the difference in milliseconds and store in day and year variable
var year_age = Math.floor(diffInMillisecond / 31536000000);
var day_age = Math.floor((diffInMillisecond % 31536000000) / 86400000);
//when birth date and month is same as today's date
if ((today.getMonth() == birthday.getMonth()) && (today.getDate() == birthday.getDate())) {
alert("Happy Birthday!");
}
var month_age = Math.floor(day_age/30);
day_age = day_age % 30;
var tMnt= (month_age + (year_age*12));
var tDays =(tMnt*30) + day_age;
//DOB is greater than today?s date, generate an error: Invalid date
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>
//Source :- https://www.javatpoint.com/calculate-age-using-javascript
//Create AgeCalculatorJS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment