Reputation: 21309
Output from Chrome 66 debug console with Hongkong timezone:
Valid date:
new Date('2018-06-30')
Sat Jun 30 2018 08:00:00 GMT+0800 (China Standard Time)
Invalid date gives T+1 value!
new Date('2018-06-31')
Sun Jul 01 2018 08:00:00 GMT+0800 (China Standard Time)
Finally... and invalid date error.
new Date('2018-06-32')
Invalid Date
Why does June 31 give T+1?
Upvotes: 0
Views: 245
Reputation: 1074208
The JavaScript Date
object is happy to handle unit rollover for you, that's all that's going on with the 2018-06-31
example — it's handling the rollover from June 30th to July 1st.
It doesn't do that for the 2018-06-32
example because 32
is an invalid value for the days field (whereas 31 isn't, it's just that June only has 30 days). The spec defines the valid ranges for the parts of the date/time string here, where we can see it says the valid values for the day of the month are 01 to 31 inclusive.
It's probably worth noting that the parsing of that ISO-8601-derived format (it isn't ISO-8601, quite) if you don't include a timezone indicator has a checkered history, sadly. ES5 specified ISO-8601 but got the meaning of the absense of a timezone indicator wrong (it said it should mean UTC, but ISO-8601 says it means local time); then ES2015 tried to fix that, but conforming to ES2016's rules would have broken a substantial amount of real-world code; and so it wasn't stabilized until ES2016, which says: Date-only forms (like yours) without a timezone indicator are UTC, date/time forms without one are local time. (It's been fine for years if you do include a timezone indicator.)
Upvotes: 2