Your age in fractional years

by OldPro

JavaScript

function noon(date) {
    // normalize date to noon that day
    return new Date(date.getFullYear(), date.getMonth(), date.getDate(), 12, 0, 0, 0);
}



// Takes a Date
function getAge(date) {
    var now = noon(new Date()),
        birthday = noon(date),
        thisBirthday = new Date(birthday),
        prevBirthday,
        nextBirthday,
        years,
        partYear,
        msInYear;
    thisBirthday.setFullYear(now.getFullYear());
    
    if (thisBirthday > now) { // not reached birthday this year
        nextBirthday = thisBirthday;
        prevBirthday = new Date(thisBirthday);
        prevBirthday.setFullYear(now.getFullYear() - 1);
    }
    else {
        nextBirthday = new Date(thisBirthday);
        nextBirthday.setFullYear(now.getFullYear() + 1);
        prevBirthday = thisBirthday;
    }
    years = prevBirthday.getFullYear() - birthday.getFullYear();
    msInYear = nextBirthday - prevBirthday;
    partYear = (now - prevBirthday) / msInYear;
    
    return years + partYear
}

// Warning,  ISO 8601 date formats (like YYYY-MM-DD) 
// are interpeted as UTC, which can make them off by one day
// in the local time zone.

function localDate(dateStr) {
    var d = new Date(dateStr);
    return new Date(d.getTime() + (d.getTimezoneOffset() * 60000));
}

alert(getAge(localDate('2000-05-15'))  + ' years');