Calculate age given the birth date in the format YYYYMMDD

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);

Solution 1:

Try this.

function getAge(dateString) {
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
}

I believe the only thing that looked crude on your code was the substr part.

Fiddle: http://jsfiddle.net/codeandcloud/n33RJ/

Solution 2:

I would go for readability:

function _calculateAge(birthday) { // birthday is a date
    var ageDifMs = Date.now() - birthday.getTime();
    var ageDate = new Date(ageDifMs); // miliseconds from epoch
    return Math.abs(ageDate.getUTCFullYear() - 1970);
}

Disclaimer: This also has precision issues, so this cannot be completely trusted either. It can be off by a few hours, on some years, or during daylight saving (depending on timezone).

Instead I would recommend using a library for this, if precision is very important. Also @Naveens post, is probably the most accurate, as it doesn't rely on the time of day.


Solution 3:

Important: This answer doesn't provide an 100% accurate answer, it is off by around 10-20 hours depending on the date.

There are no better solutions ( not in these answers anyway ). - naveen

I of course couldn't resist the urge to take up the challenge and make a faster and shorter birthday calculator than the current accepted solution. The main point for my solution, is that math is fast, so instead of using branching, and the date model javascript provides to calculate a solution we use the wonderful math

The answer looks like this, and runs ~65% faster than naveen's plus it's much shorter:

function calcAge(dateString) {
  var birthday = +new Date(dateString);
  return ~~((Date.now() - birthday) / (31557600000));
}

The magic number: 31557600000 is 24 * 3600 * 365.25 * 1000 Which is the length of a year, the length of a year is 365 days and 6 hours which is 0.25 day. In the end i floor the result which gives us the final age.

Here is the benchmarks: http://jsperf.com/birthday-calculation

To support OP's data format you can replace +new Date(dateString);
with +new Date(d.substr(0, 4), d.substr(4, 2)-1, d.substr(6, 2));

If you can come up with a better solution please share! :-)