3

This is a bizarre but I'm sure there's a perfectly good explanation.

My team and I recently discovered when using java's LocalDate and sending it back to the frontend with the default string format "YYYY-MM-DD", Javascript will automatically create a date assuming that the string was UTC, so living in ET zone, it automatically subtracts -5 hours.

Annoying, but we get it.

However, when we send it back with time as so "YYYY-MM-DDThh:mm:ss", it parses it as a local date. Ok, weird... but it gets weirder.

Now the bizarre part, if we send the string without the 0 padding on the date as so "YYYY-MM-D" it parses it as a local date. Why?

Here's an example:

new Date("2017-12-09")
// output: Fri Dec 08 2017 19:00:00 GMT-0500 (Eastern Standard Time)
new Date("2017-12-9")
// output: Sat Dec 09 2017 00:00:00 GMT-0500 (Eastern Standard Time)

Why is this???

David Domingo
  • 461
  • 4
  • 13
  • 1
    In some browsers, `new Date("2017-12-9")` produces an invalid date. Parsing of non–standard strings (i.e. anything not supported by [*ECMA-262*](http://ecma-international.org/ecma-262/9.0/#sec-date.parse)) is implementation dependent. – RobG Nov 29 '18 at 20:19

1 Answers1

4

The answer relies on your browser implementation.

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.

Errorname
  • 2,228
  • 13
  • 23
  • 1
    And ISO 8601 requires padding, so `2017-12-09` is ISO 8601 while `2017-12-9` isn’t. So your quote seems to explain. – Ole V.V. Nov 29 '18 at 15:49
  • Is there any reason why? I don't understand why they would treat date only and datetime strings differently. – David Domingo Nov 29 '18 at 15:54
  • Well, Javascript is an "old" language that went through a lot of changes and battles between implementations (looking at you, IE). Javascript has been known to be a language with questionnable designing choices. This explain why, as developers, we often use librairies to abstract theses strange choices. (If you want to learn more about JS history, I suggest: https://auth0.com/blog/a-brief-history-of-javascript/) – Errorname Nov 29 '18 at 15:58
  • Cool! Thanks! I usually use momentjs, so I'm not used to running into these date curiosities. – David Domingo Nov 29 '18 at 16:03
  • 1
    You're welcome. Also, check out `date-fns` too, that's a good lightweight alternative to moment – Errorname Nov 29 '18 at 16:17