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);
I think that could be simply like that:
Works also with a timestamp
Here's the simplest, most accurate solution I could come up with:
And here is a sample that will consider Feb 29 -> Feb 28 a year.
It even works with negative age!
I've did some updated to one previous answer.
I hope that helps :D
Some time ago I made a function with that purpose:
It takes a Date object as input, so you need to parse the
'YYYYMMDD'
formatted date string:Adopting from naveen's and original OP's posts I ended up with a reusable method stub that accepts both strings and / or JS Date objects.
I named it
gregorianAge()
because this calculation gives exactly how we denote age using Gregorian calendar. i.e. Not counting the end year if month and day is before the month and day of the birth year.