有多种方法来计算月和日。没有进一步限制,即使结果可能不同,所有纠正都是正确的。
例如从9月27日至11月一日可以是任一
这是一种可能的解决方案。
// 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到:1天1个月//而不是1个月和5天
- 12/31 03/01到:每日1 2个月//而不是1个月和29天
- 5月31日至06/30:30天
- 1月31日至03/30:30天和1个月//而不是1个月和27个月天
- 10/27/2010至2014年8月26日:30天9个月至3年
http://stackoverflow.com/questions/7763327/how-to-calculate-date-difference -in-javascript应该做你所需要的大概 – Rhumborl 2014-09-27 10:26:02
我希望你知道01月是二月。 – Robert 2014-09-27 11:17:25
是的。我有两个月的问题。 – krutssss 2014-09-29 06:44:23