gistfile1.txt /** * 当前日期增减指定天数后,返回新日期 * @param {Number} days 可正可负,参考C# DateTime.AddDays方法 * @returns {Date} 结果日期 */Date.prototype.addDays = function(days) { return new Date(this.ge
/**
* 当前日期增减指定天数后,返回新日期
* @param {Number} days 可正可负,参考C# DateTime.AddDays方法
* @returns {Date} 结果日期
*/
Date.prototype.addDays = function(days) {
return new Date(this.getTime() + days * 24 * 60 * 60 * 1000);
}
/**
* 当前日期增减指定月分数后,返回新日期
* @param {Number} months 可正可负,参考C# DateTime.AddMonths方法(处理了大小月份及闰年的情况)
* @returns {Date} 结果日期
*/
Date.prototype.addMonths = function (months) {
var maxDayOfMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var isLeapYear = function(year) {
return (year % 4 === 0) && (year % 100 !== 0 || year % 400 === 0);
}
var thisYear = this.getFullYear();
var thisMonth = this.getMonth() + 1;
var thisDate = this.getDate();
var newMonth = thisMonth + months;
var newYear = thisYear;
var newDate = thisDate;
if (newMonth > 12) {
newYear += Math.floor(newMonth / 12);
newMonth = newMonth % 12;
}
if (newMonth <= 0) {
newYear += (0 - (Math.floor(Math.abs(newMonth) / 12) + 1));
newMonth = 12 - Math.abs(newMonth) % 12;
}
//处理天数是否合法
var maxDay = maxDayOfMonths[newMonth - 1];
(isLeapYear(newYear) && newMonth === 2) && (maxDay += 1);
(newDate > maxDay) && (newDate = maxDay);
return new Date(Date.parse(newYear + '-' + newMonth + '-' + newDate));
}
