年龄计算不正确
Age is not getting calculated correctly?
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。
相关文章:
- 在 javascript 中计算不正确的问题
- date.js计算不正确
- jQuery重新计算总计和值,但最终总数不正确
- 在瞬间js中计算周数不正确
- jQuery 偏移量在某些页面上计算不正确
- 计算字符串时答案不正确
- 年龄计算不正确
- 为什么我在 JavaScript 中得到这个不正确的算术计算
- 使用点后有四位数字的十进制值计算中的结果不正确
- 当文本具有特殊字符时,offsetWidth计算不正确
- 使用Javascript从输入数组中查找平均值-计算不正确
- JavaScript计算结果不正确
- 为什么这个JavaScript函数在网站第一次加载时不能正确计算,但之后工作正常?
- Ng-if表达式计算不正确
- 罗马数字转换情况不正确计算
- computeDistanceBetween似乎计算不正确
- Angularjs的ngDisabled比较表达式不能正确计算
- 文本框值计算不正确
- 沙狐不正确地计算高度
- If语句计算不正确