我想在JavaScript中为日期添加月份。

例如:我插入日期06/01/2011(格式mm/dd/yyyy),现在我想在这个日期上加上8个月。我希望结果是02/01/2012。

所以当增加月份时,年份也会增加。


我强烈建议你看一看datejs。通过它的api,添加一个月(以及许多其他日期功能)变得非常简单:

var one_month_from_your_date = your_date_object.add(1).month();

datejs的优点在于它处理边缘情况,因为技术上你可以使用原生Date对象和它的附加方法来做到这一点。但你最终会在边缘情况下抓狂,datejs已经帮你解决了。

而且它是开源的!


截至2019年6月25日更正:

var newDate = new Date(date.setMonth(date.getMonth()+8));

老 从这里开始:

var jan312009 = new Date(2009, 0, 31);
var eightMonthsFromJan312009  = jan312009.setMonth(jan312009.getMonth()+8);

我看了一下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日期对象。感谢Coolite公司!

使用:

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 = "Feb 29 2012"

result2 = "Feb 28 2011"