0

I'm trying to use JavaScript's setMonth(...) to add one month to current date. Everything seemed to work fine until today, the last day of the month. I'm seeing some odd behavior.

Here's the code:

var date = new Date();
console.log('Current Date', date);

var currentMonth = date.getMonth();
console.log('Current Month', currentMonth);

var nextMonth = parseInt(currentMonth) + 1
console.log('Next Month', nextMonth);

date.setMonth(nextMonth);
console.log('Next date month ID', date.getMonth())
console.log('Next Month Date', date);

And here is the output:

Current Date Wed May 31 2017 11:58:50 GMT-0700 (MST)
Current Month 4
Next Month 5
Next date month ID 6
Next Month Date Sat Jul 01 2017 11:58:50 GMT-0700 (MST)

Somehow, after setting the month, we are skipping June and going straight to July, even though we have hours left before June starts.

Here is JSFIDDLE

smr5
  • 2,593
  • 6
  • 39
  • 66
  • 2
    There's no June 31st. You need to normalize the time of day before you advance time. – André Dion May 31 '17 at 19:14
  • Ooo, I see the problem now. Thanks. I need to specify the date as well in the method. – smr5 May 31 '17 at 19:22
  • I think you seem to use it wrong way. Because the following month doesn't have day 31. Therefore, it skips to the next month. new Date(2017, 6, 01); Use setDate instead. var d = new Date(2017,4,31); d.setDate(d.getDate() + 1 ); – Yergalem May 31 '17 at 19:39
  • Also see [*Subtracting 1 month to 2015-12-31 gives 2015-12-01*](https://stackoverflow.com/questions/36427965/subtracting-1-month-to-2015-12-31-gives-2015-12-01/36428762#36428762). – RobG Jun 01 '17 at 00:20

1 Answers1

1

The issue is that today is the 31st and if you don't give it the day parameter it uses the day of the month object before you set the month.

If you just use:

date.setMonth(nextMonth,1);

You'll get the first of the next month.

Here's more information about the set month function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMonth

Avitus
  • 15,640
  • 6
  • 43
  • 53
  • Thank you. I didn't read the documentation throughly. Thought i didn't had to specify `1`. But your post solves my issue. – smr5 May 31 '17 at 19:20