年龄计算不正确

Age is not getting calculated correctly?

本文关键字:不正确 计算      更新时间:2023-09-26
function getAge(dateString1,dateString2) {
    var today = new Date(dateString2);
    var birthDate = new Date(dateString1);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
}
我知道

这有点谜语,但我知道这个函数会产生错误的结果,但不确定什么时候会?DateString 是 JavaScript 中的 std. date 对象。

Input On which it produced faulty results 
DateString1
1988-04-05 00:00:00
1965-05-06 00:00:00
1971-03-14 00:00:00
1975-11-10 00:00:00
1981-10-21 00:00:00
1974-06-01 00:00:00
1988-08-11 00:00:00
DateString2
2016-03-31 00:00:00

评估后的年龄绝不能达到>=65,但对于这些值,情况并非如此。

如果您想简单地将年龄显示为完成年份,这是一个很好的技巧:

function getAgeInFullYears(birthdate, today) {
    // These two lines are not necessary if function is called with proper Date objects
    birthdate = new Date(birthdate);
    today = new Date(today);
    birthdate = birthdate.getFullYear() * 10000 +
                birthdate.getMonth() * 100 +
                birthdate.getDate();
    today = today.getFullYear() * 10000 +
            today.getMonth() * 100 +
            today.getDate();
    return Math.floor((today - birthdate) / 10000);
}

它的工作原理是将日期"转换"为 yyyymmdd 形式的十进制数,例如 1974 年 4 月 27 日的 19,740,427。然后,它从当前日期中减去出生日期,将结果除以 10000 并跳过余数。

使用的因子 100

和 10000 实际上是非常任意的,只要月因子为>= 31 且年份因子为>=(12 * 月因子),任何因素都有效。

例如,调用 getAgeInFullYears('1988-04-05', '2016-02-18') 返回 27。