如何在JavaScript中添加月份到日期?

时间:2011-04-13 06:03:54

标签: javascript date

我想在JavaScript中添加几个月的日期。

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

因此,在增加月份时,年份也可能会增加。

4 个答案:

答案 0 :(得分:198)

来自here

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

答案 1 :(得分:155)

将您的日期拆分为年,月和日组件,然后使用Date

var d = new Date(year, month, day);
d.setMonth(d.getMonth() + 8);

日期将负责确定年份。

答案 2 :(得分:85)

我查看了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 Inc!

使用:

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日”

答案 3 :(得分:13)

我强烈建议您查看datejs。使用它的api,添加一个月(以及许多其他日期功能)变得很简单:

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

datejs的好处在于它处理边缘情况,因为从技术上讲,您可以使用本机Date对象及其附加方法来执行此操作。但是你最终会将头发拉过边缘,datejs为你照顾好了。

另外它是开源的!