如何在JavaScript中为日期添加月份? [重复]

问题描述

|                                                                                                                   这个问题已经在这里有了答案:                                                      

解决方法

自25.06.2019起更正:
var newDate = new Date(date.setMonth(date.getMonth()+8));
旧 从这里:
var jan312009 = new Date(2009,31);
var eightMonthsFromJan312009  = jan312009.setMonth(jan312009.getMonth()+8);
    ,将日期分为年,月和日部分,然后使用日期:
var d = new Date(year,month,day);
d.setMonth(d.getMonth() + 8);
日期将确定年份。     ,我看了一下datejs,并去除了在处理极端情况的日期(months年,较短的月份等)中添加月份所需的代码:
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][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日”     ,我强烈建议您看一下datejs。使用它的api,添加一个月变得很简单(以及许多其他日期功能):
var one_month_from_your_date = your_date_object.add(1).month();
datejs
的优点在于它可以处理边缘情况,因为从技术上讲,您可以使用本机
Date
对象及其附加方法来执行此操作。但是最后,您将头发拉出了边缘保护套,ѭ6帮您解决了。 加上它是开源的!     

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...