How can I calculate an age in years, given a birth date of format YYYYMMDD? Is it possible using the Date()
function?
I am looking for a better solution than the one I am using now:
var dob = '19800810';
var year = Number(dob.substr(0, 4));
var month = Number(dob.substr(4, 2)) - 1;
var day = Number(dob.substr(6, 2));
var today = new Date();
var age = today.getFullYear() - year;
if (today.getMonth() < month || (today.getMonth() == month && today.getDate() < day)) {
age--;
}
alert(age);
Two more options:
You may use this for age restriction in your form -
To get the age when european date has entered:
With momentjs:
One more possible solution with moment.js:
Works perfect for me, guys.