有多种方法可以计算月份和日期。如果没有进一步的限制,即使结果可能不同,所有正确的结果都是正确的。
例如,从 9 月 27 日到 11 月 1 日可以是
这是一种可能的解决方案。
// swap dates if difference would be negative
if (firstDate.getTime() > secondDate.getTime()) {
var tmp = firstDate;
firstDate = secondDate;
secondDate = tmp;
}
var years = secondDate.getFullYear() - firstDate.getFullYear();
var months = secondDate.getMonth() - firstDate.getMonth();
var days = secondDate.getDate() - firstDate.getDate();
// prevent negative amount of days by breaking up months
for (var i = 0; days < 0; ++i) {
// while the day difference is negative
// we break up months into days, starting with the first
months -= 1;
days += new Date(
firstDate.getFullYear(),
firstDate.getMonth() + 1 + i,
0, 0, 0, 0, 0
).getDate();
}
// prevent negative amount of months by breaking up years
if (months < 0) {
years += Math.floor(months / 12);
months = (months % 12 + 12) % 12;
}
// print the result
console.log([
{amount: days, unit: 'day'},
{amount: months, unit: 'month'},
{amount: years, unit: 'year'},
].filter(value => value.amount).map(value =>
value.amount === 1 ?
`${value.amount} ${value.unit}` :
`${value.amount} ${value.unit}s`
).reduce((result, part, index, parts) =>
index > 0 ? index === parts.length - 1 ?
`${result} and ${part}` :
`${result}, ${part}` :
`${part}`,
`0 days`
));
例子:
- 02/12 至 02/22:10 天
- 09/27 至 11/01:4 天零 1 个月 // 而不是 1 个月又 5 天
- 12/31 至 03/01:1 天 2 个月 // 而不是 1 个月 29 天
- 05/31 至 06/30:30 天
- 01/31 至 03/30:30 天零 1 个月 // 而不是 1 个月零 27 天
- 2010年10月27日至2014年8月26日:30天9个月3年