Age (+leap year) calculation in Javascript?

前端 未结 3 1291
-上瘾入骨i
-上瘾入骨i 2021-02-09 15:34

I\'ve read this question but there were many comments which some said it was accurate and some said it wasn\'t accurate.

Anyway I have this code which calc pers

3条回答
  •  野的像风
    2021-02-09 16:20

    The calculation is not correct, because of the assumption that a year is 365.242 days.

    A year is by average 365.242 days, but there is no actual year that is 365.242 days. A year is either exactly 365 or 366 days (ignoring the small detail that there are some years that have leap seconds.)

    To calculate the age as fractional years exactly, you would have to calculate the whole number of years up to the last birthday, and then calculate the fraction for the current year based on how many days the current year has.


    You can use code like this to calculate the exact age in years:

    function isLeapYear(year) {
        var d = new Date(year, 1, 28);
        d.setDate(d.getDate() + 1);
        return d.getMonth() == 1;
    }
    
    function getAge(date) {
        var d = new Date(date), now = new Date();
        var years = now.getFullYear() - d.getFullYear();
        d.setFullYear(d.getFullYear() + years);
        if (d > now) {
            years--;
            d.setFullYear(d.getFullYear() - 1);
        }
        var days = (now.getTime() - d.getTime()) / (3600 * 24 * 1000);
        return years + days / (isLeapYear(now.getFullYear()) ? 366 : 365);
    }
    
    var date = '1685-03-21';
    
    alert(getAge(date) + ' years');
    

    Demo: http://jsfiddle.net/Guffa/yMxck/

    (Note: the days is also a fractional value, so it will calculate the age down to the exact millisecond. If you want whole days, you would add a Math.floor around the calculation for the days variable.)

提交回复
热议问题