我想在JavaScript中为日期添加月份。
例如:我正在插入日期06/01/2011 (格式为mm/dd/yyyy),现在我想在此日期上添加8个月。我希望结果是02/01/2012。
因此,当添加月份时,年份也可能会增加。
发布于 2011-04-13 14:11:18
截至2019年6月25.06.时更正的:
var newDate = new Date(date.setMonth(date.getMonth()+8));来自here的旧
var jan312009 = new Date(2009, 0, 31);
var eightMonthsFromJan312009 = jan312009.setMonth(jan312009.getMonth()+8);发布于 2011-04-13 14:13:14
发布于 2012-11-30 03:58:09
我看了一下datejs,并去掉了向日期添加月份所需的代码,以处理边缘情况(闰年、较短的月份等):
Date.isLeapYear = function (year) {
return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0));
};
Date.getDaysInMonth = function (year, month) {
return [31, (Date.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
};
Date.prototype.isLeapYear = function () {
return Date.isLeapYear(this.getFullYear());
};
Date.prototype.getDaysInMonth = function () {
return Date.getDaysInMonth(this.getFullYear(), this.getMonth());
};
Date.prototype.addMonths = function (value) {
var n = this.getDate();
this.setDate(1);
this.setMonth(this.getMonth() + value);
this.setDate(Math.min(n, this.getDaysInMonth()));
return this;
};这会将"addMonths()“函数添加到任何应该处理边缘情况的javascript date对象。感谢酷派公司!
使用:
var myDate = new Date("01/31/2012");
var result1 = myDate.addMonths(1);
var myDate2 = new Date("01/31/2011");
var result2 = myDate2.addMonths(1);->> newDate.addMonths -> mydate.addMonths
result1 =“2012年2月29日”
result2 =“2011年2月28日”
https://stackoverflow.com/questions/5645058
复制相似问题