在 JavaScript 中为日期添加一个月

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2848673/
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-08-23 02:09:41  来源:igfitidea点击:

Add One Month to a Date in JavaScript

javascriptjquerydatedatetime

提问by leora

I have an input field that needs to be incremented by one month using the JavaScript Date object. Below is an example of an effort I have made in incrementing the month. The issue with this seems to be that it will display 0 as January and does not increment the year.

我有一个需要使用 JavaScript 日期对象递增一个月的输入字段。下面是我在增加月份方面所做的努力的一个例子。与此有关的问题似乎是它会将 0 显示为一月,并且不会增加年份。

nDate.setDate(nDate.getDate());
inputBox1.value = (nDate.getMonth() + 1) + "/" + (nDate.getDate()) + "/" +  (nDate.getFullYear());

回答by Salman A

Use Date.setMonth:

使用Date.setMonth

var d = new Date(2000, 0, 1); // January 1, 2000
d.setMonth(d.getMonth() + 1);
console.log(d.getFullYear(), d.getMonth() + 1, d.getDate());

Date.setMonthis range proof i.e. months other than 0...11 are adjusted automatically.

Date.setMonth是范围证明,即自动调整 0...11 以外的月份。

回答by Mark Pope

You'll have to get the text out of the text box, which you can then pass to the Date() constructor:

您必须从文本框中获取文本,然后可以将其传递给 Date() 构造函数:

var d = new Date(text);

var d = new Date(text);

Then format the date string:

然后格式化日期字符串:

var str = d.getDate(), d.getMonth() + 1, d.getFullYear()

var str = d.getDate(), d.getMonth() + 1, d.getFullYear()

And set the test box to that value

并将测试框设置为该值