Add One Month to a Date in JavaScript
84,527
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.
Author by
leora
Updated on July 06, 2022Comments
-
leora almost 2 years
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) + "/" + (nDate.getDate()) + "/" + (nDate.getFullYear());
-
leora about 14 yearswhat about december --> january
-
Mark Pope about 14 yearsHmm, I thought it rolled, but maybe you'll have to explicitly check for that. Or there could be a better way entirely
-
leora about 14 yearsi dont understand your line how its creating a date, it seems like it will create something like 30, 4, 1002
-
Mark Pope about 14 yearsMy bad, copy+pasted from one of my apps that does it slightly differently!
-
Alnitak over 11 years@leora adding one month to December will cause a year roll. What I don't know is what happens if you roll from the end of a long month into a shorter month.