问题
My code:
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)));
}
Example 1:
If I was born in
1993-year;
04-month(april);
26-date
I will pass 930426 as value to test function and the result would be 27 which is correct
But in Example 2:
If I was born in:
1993-year;
09-month(september);
14-date;
I will pass 930914 as value to test function and result would be 27, but it's not correct because my birthday is still not come and i'm still 26 years old.
How can I fix this ?
回答1:
Because 26.9 is still regarded as age of 26, so you should use .floor instead
function test(val) {
year = +val.slice(0, 2) // get year
month = val.slice(2, 4) // get month
date = val.slice(4, 6) // get date
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(diff / 365.25)
console.log("Age", Math.floor(diff / 365.25))
}
test("930426")
test("930914")
来源:https://stackoverflow.com/questions/63830283/how-to-take-the-differences-between-two-dates-depending-on-the-date-of-birth