我们使用以下代码。
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date(2008,01,12);
var secondDate = new Date(2008,01,22);
var diffDays = Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay));
但我们无法在他们之间找到月份和日期。 我想要假设开始日期是27-sep-2014,结束日期是1-nov-2014。结果将是1个月和5天。
答案 0 :(得分:3)
有多种计算月和日的方法。没有进一步的限制,即使结果可能不同,所有正确的都是正确的。
例如,从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`
));
示例:
答案 1 :(得分:1)
试试这个
var oneDay = 24*60*60*1000;
var firstDate = new Date(2007,01,12);
var secondDate = new Date(2008,01,22);
var diffDays = Math.abs((firstDate.getTime() - secondDate.getTime()));
var result = '',
years, months, days;
if((years = diffDays / (365 * oneDay)) > 1){
result += Math.floor(years) + ' Year(s)';
diffDays %= (365 * oneDay);
}
if((months = diffDays / (30 * oneDay)) > 1){
result += Math.floor(months) + ' Month(s)';
diffDays %= (30 * oneDay);
}
result += (diffDays / oneDay) + ' Days(s)';
alert(result);
&#13;