Fix JavaScript setMonth() behavior #822
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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 to 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:
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 and always sets the month to the one requested.