如果只是计算,那么您可以通过 d.setMonth(d.getMonth() + 1) 添加月份。这使得 Date 完成了计算每个月有多长的所有麻烦事。
var initial_value = 5,
initial_date = new Date(2014, 0, 1), // January
end_date = new Date(2014, 3, 1); // April
var spent = 2;
var value = initial_value,
date = new Date(initial_date);
while (date.setMonth(date.getMonth() + 1), date <= end_date)
value += 1;
value -= spent;
value; // 6
此方法适用于每月 < 29 的几天,对于 29 <= x <= 31 的几天,您将需要额外检查
即检查到那时它改变了多少个月,如果不是1,在这些情况下你想要什么行为?
如果你总是想要一个月的最后一天,那么它只比上面长几个步骤,
d.setDate(1); // go to a "safe day" to change months
d.setMonth(d.getMonth() + 2); // go 2 months forward
d.setDate(0); // roll back to the last day of the previous month
我一直在玩的一些额外的东西
var dates = (function () {
function isLeapYear(year) {
if (year % 4) // not divisible by 4
return false;
if (year % 100) // not divisible by 100
return true;
if (year % 400) // not divisible by 400
return false;
return true;
}
return {
year: new Date().getUTCFullYear(),
get leapYear() { return isLeapYear(this.year); },
isLeapYear: isLeapYear,
get total() { return 365 + isLeapYear(this.year); },
0: 31,
get 1() { return 28 + isLeapYear(this.year); },
2: 31,
3: 30,
4: 31,
5: 30,
6: 31,
7: 31,
8: 30,
9: 31,
10: 30,
11: 31
};
}());