首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在JavaScript中为日期添加月份?

问如何在JavaScript中为日期添加月份?
EN

Stack Overflow用户
提问于 2011-04-13 14:03:54
回答 4查看 541.5K关注 0票数 301

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

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

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

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2011-04-13 14:11:18

截至2019年6月25.06.时更正的:

代码语言:javascript
复制
var newDate = new Date(date.setMonth(date.getMonth()+8));

来自here的旧

代码语言:javascript
复制
var jan312009 = new Date(2009, 0, 31);
var eightMonthsFromJan312009  = jan312009.setMonth(jan312009.getMonth()+8);
票数 378
EN

Stack Overflow用户

发布于 2011-04-13 14:13:14

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

代码语言:javascript
复制
var d = new Date(year, month, day);
d.setMonth(d.getMonth() + 8);

日期将负责确定年份。

票数 180
EN

Stack Overflow用户

发布于 2012-11-30 03:58:09

我看了一下datejs,并去掉了向日期添加月份所需的代码,以处理边缘情况(闰年、较短的月份等):

代码语言:javascript
复制
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对象。感谢酷派公司!

使用:

代码语言:javascript
复制
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日”

票数 117
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5645058

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档