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.

Share:
84,527
leora
Author by

leora

Updated on July 06, 2022

Comments

  • leora
    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
    leora about 14 years
    what about december --> january
  • Mark Pope
    Mark Pope about 14 years
    Hmm, I thought it rolled, but maybe you'll have to explicitly check for that. Or there could be a better way entirely
  • leora
    leora about 14 years
    i dont understand your line how its creating a date, it seems like it will create something like 30, 4, 1002
  • Mark Pope
    Mark Pope about 14 years
    My bad, copy+pasted from one of my apps that does it slightly differently!
  • Alnitak
    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.