2

How do I calculate the age of a person who enters his date of birth in a YYYY/MM/DD format in a textbox?

This is what i've tried so far:

function OnClick() {
var txtDate = $("#txtDate").val();
var date1 = new Date();
date1.setFullYear(txtDate);
var d1 = date1.getFullYear();
var date2 = new Date();
var d2 = date2.getFullYear();
var age = d2 - d1;
document.getElementById("Diven").innerHTML = age;   
}

I want to be able to calculate the exact age, so far I've only managed to do it by year using JQuery.

Help is appreciated

1 Answers1

1

I've actually saved a little pile of code to do this,

This should do the trick:

var today = new Date();
var inputBirthDate= new Date(birthYear, birthMonth - 1, birthDay);
var age = today.getFullYear() - inputBirthDate.getFullYear();
var month = today.getMonth() - inputBirthDate.getMonth();
if (month < 0 || (month === 0 && today.getDate() < inputBirthDate.getDate())) {
   age--;
}
console.log(age);

The code above will return you the correct age based on input birth date. The " -1 " on month is because months are counted from "00"

Dr Cox
  • 149
  • 6
  • 35