1

The operation date not working as expected when setting a next or previous month that no have the day that is in the actual date

>var date = new Date('2018/10/31');
undefined
>date
Wed Oct 31 2018 00:00:00 GMT-0600 (hora estándar central)
>date.setMonth(date.getMonth() + 1);
1543644000000
>date
Sat Dec 01 2018 00:00:00 GMT-0600 (hora estándar central)

Is this a bug and should it be reported or considered as the expected behavior?

ADyson
  • 57,178
  • 14
  • 51
  • 63
Johan.CR
  • 25
  • 3

1 Answers1

1

It's documented behaviour. To quote from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMonth for example:

If a parameter you specify is outside of the expected range, setMonth() attempts to update the date information in the Date object accordingly. For example, if you use 15 for monthValue, the year will be incremented by 1, and 3 will be used for month.

The current day of month will have an impact on the behaviour of this method. Conceptually it will add the number of days given by the current day of the month to the 1st day of the new month specified as the parameter, to return the new date. For example, if the current value is 31st August 2016, calling setMonth with a value of 1 will return 2nd March 2016. This is because in 2016 February had 29 days.

In your case, it's doing what's described above in the second paragraph: you've changed the month to November, but you haven't changed the day. And of course there's no 31st of November, so JavaScript automatically sets the date to the next valid date instead, which is 1st December.

ADyson
  • 57,178
  • 14
  • 51
  • 63
  • Thats right, I leave this example of the same link that I consider more clear: "For example, if the current value is 31st August 2016, calling setMonth with a value of 1 will return 2nd March 2016. This is because in 2016 February had 29 days." – Johan.CR Oct 29 '18 at 22:30
  • @Johan.CR ok that's also a good example, but your suggested edit doesn't reflect your comment, and instead it removes the important detail which both your quote and my example are talking about. I've edited it to use that quote as well. – ADyson Oct 29 '18 at 22:34
  • 1
    @Bravo see the edit about 3 seconds after you posted your comment :-) – ADyson Oct 29 '18 at 22:36
  • 1
    Timing has never been my strength :p – Bravo Oct 29 '18 at 22:36