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);
here is a simple way of calculating age:
With momentjs "fromNow" method, This allows you to work with formatted date, ie: 03/15/1968
var dob = document.getElementByID("dob"); var age = moment(dob.value).fromNow(true).replace(" years", "");
//fromNow(true) => suffix "ago" is not displayed //but we still have to get rid of "years";
As a prototype version
}
Alternate solution, because why not:
I just had to write this function for myself - the accepted answer is fairly good but IMO could use some cleanup. This takes a unix timestamp for dob because that was my requirement but could be quickly adapted to use a string:
Notice I've used a flat value of 31 in my measureDays function. All the calculation cares about is that the "day-of-year" be a monotonically increasing measure of the timestamp.
If using a javascript timestamp or string, obviously you'll want to remove the factor of 1000.
Here's my solution, just pass in a parseable date: