在 JavaScript 中为日期添加月份

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12793045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:08:20  来源:igfitidea点击:

Adding months to a Date in JavaScript

phpjavascript

提问by RobG

Possible Duplicate:
Javascript function to add X months to a date

可能的重复:
将 X 个月添加到日期的 Javascript 函数

I'd like to add 2 months to a user-input end date. How can I add 2 months to the end date and display it?

我想为用户输入的结束日期添加 2 个月。如何将 2 个月添加到结束日期并显示它?

/**
* Click "Cal" on end date
*/
function getEndDate() {
if(!document.getElementById('startdate').value.length) {
    alert("Start date must be set first.");
}
else {
    prevEndDate = document.getElementById('enddate').value;
    displayCalendar(document.forms[0].enddate,'yyyy/mm/dd',
        document.getElementById('enddatebutton'));
}
}

/**
* Click "Cal" on expiry date
*/
function getExpiryDate() {
if(!document.getElementById('enddate').value.length) {
    alert("End date must be set first.");
}
else {
    prevExpiryDate = document.getElementById('expirydate').value;
    displayCalendar(document.forms[0].expirydate,'yyyy/mm/dd',
        document.getElementById('expirydatebutton'));
 }
}

Any help is appreciated. Thanks!

任何帮助表示赞赏。谢谢!

回答by RobG

You need to get business rules for adding months. The simple solution is:

您需要获取添加月份的业务规则。简单的解决方法是:

function addMonths(dateObj, num) {
  return dateObj.setMonth(dateObj.getMonth() + num);
}

However, that will change 31 July to 31 September, which will be converted to 1 October. Also, 31 January plus 1 month is 31 February which will be converted to 2 or 3 March depending on whether it's a leap year or not.

但是,这会将 7 月 31 日更改为 9 月 31 日,后者将转换为 10 月 1 日。此外,1 月 31 日加 1 个月是 2 月 31 日,这将根据是否为闰年转换为 2 月或 3 日。

You might expect the first to be 30 September and the second to be 28 or 29 February (depending on whether it's a leap year or not).

您可能期望第一个是 9 月 30 日,第二个是 2 月 28 日或 29 日(取决于它是否是闰年)。

So if you want "end of months" be observed, you need to do something like:

因此,如果您想观察“月末”,则需要执行以下操作:

function addMonths(dateObj, num) {

    var currentMonth = dateObj.getMonth() + dateObj.getFullYear() * 12;
    dateObj.setMonth(dateObj.getMonth() + num);
    var diff = dateObj.getMonth() + dateObj.getFullYear() * 12 - currentMonth;

    // If don't get the right number, set date to 
    // last day of previous month
    if (diff != num) {
        dateObj.setDate(0);
    } 
    return dateObj;
} 

But check with whoever is responsible for the business rules that that is what they want.

但是请与负责他们想要的业务规则的人联系。

Edit

编辑

The above works well, but in response to McShaman's comment here is a version with a simpler check for the month roll–over:

上面的方法效果很好,但为了回应 McShaman 的评论,这里有一个版本,对月份滚动进行了更简单的检查:

function addMonths(date, months) {
  var d = date.getDate();
  date.setMonth(date.getMonth() + +months);
  if (date.getDate() != d) {
    date.setDate(0);
  }
  return date;
}

// Add 12 months to 29 Feb 2016 -> 28 Feb 2017
console.log(addMonths(new Date(2016,1,29),12).toString());

// Subtract 1 month from 1 Jan 2017 -> 1 Dec 2016
console.log(addMonths(new Date(2017,0,1),-1).toString());

// Subtract 2 months from 31 Jan 2017 -> 30 Nov 2016
console.log(addMonths(new Date(2017,0,31),-2).toString());

// Add 2 months to 31 Dec 2016 -> 28 Feb 2017
console.log(addMonths(new Date(2016,11,31),2).toString());

回答by Ravi Kumar

Split your date into year, month, and day components then use Date:

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

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

Date will take care of fixing the year.

日期将负责确定年份。

Possible Duplicate of How to add months to a date in JavaScript?

如何在 JavaScript 中向日期添加月份的可能重复