【发布时间】:2020-09-10 21:22:10
【问题描述】:
我的代码:
function test(val) {
year = parseInt(val.slice(0,2)); // get year
month = parseInt(val.slice(2,4)); // get month
date = val.slice(4,6); // get date
if (month > 40) { // For people born after 2000, 40 is added to the month. (it is specific for my case)
year += 2000;
month -= 40;
} else {
year += 1900;
}
date = new Date(year, month-1, date, 0, 0);
date_now = new Date();
var diff =(date_now.getTime() - date.getTime()) / 1000;
diff /= (60 * 60 * 24);
console.log(Math.abs(Math.round(diff/365.25)));
}
示例 1:
如果我出生在
1993-year;
04-month(april);
26-date
我会将930426 作为值传递给测试函数,结果将是正确的 27
但是在示例2中:
如果我出生在:
1993-year;
09-month(september);
14-date;
我会将930914 作为值传递给测试函数,结果是 27,但这不正确,因为我的生日还没到,我还 26 岁。
我该如何解决这个问题?
【问题讨论】:
-
我不想使用moment.js
标签: javascript algorithm date