开发者

Add One Month to a Date in JavaScript

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.

nDate.setDate(nDate.getDate());
inputBox1.value = (nDate.getMonth() + 1) + 开发者_如何学Python"/" + (nDate.getDate()) + "/" +  (nDate.getFullYear());


Use 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.setMonth is range proof i.e. months other than 0...11 are adjusted automatically.


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

var d = new Date(text);

Then format the date string:

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

And set the test box to that value

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜