timrwood/moment — pull request #822 by jwarkentin (2013-05-31 20:29:54+00:00)
Title: Fix JavaScript setMonth() behavior

JavaScript does some weird stuff with setMonth(). This change makes its behavior more consistent.

If you have a moment object with a date around the end of the month and you try to change the month do a month that doesn't have that many days you end up with an unexpected result. You can see this exhibited using moment like this:

```
>>> var m = moment('20130531', 'YYYYMMDD');
>>> m.month();
6
>>> m.month(5);
>>> m.month();
6
```

In JS the `setMonth()` method sets the month and then applies the date and rolls over into the next month if the date (e.g. 31) is higher than the last day of the month.

While this is the normal behavior of the JS `Date` object, I would argue that it is the wrong behavior. It causes bugs that users unfamiliar with the oddities of the language won't expect. In addition the date you end up with is somewhat arbitrary and not helpful in any case I can imagine because it's not consistent or predictable without extra logic. If I'm using an object and I try to explicitly set the month I want the object to go to that month, not occasionally end up on both a different month AND date from what I expect.

If the month doesn't have enough days it's much less buggy or unexpected for it to consistently go to the last day of the month than to end up on some day toward the start of the month depending on what day of the month it is and what month I'm switching to.

In my particular case it caused a bug that could only be observed on certain days of certain months, like today. In my code it creates a new moment object and then tries to set the month based on a value returned from the server. But since the object was created today it causes it to set the month wrong. If I tried the exact same thing yesterday it would have worked fine. At least with this fix it creates consistent and predictable behavior.