Calculate age given the birth date in the format YYYYMMDD

Francisc picture Francisc · Oct 30, 2010 · Viewed 420.5k times · Source

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:

Answer

naveen picture naveen · Aug 17, 2011

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/