为什么 JS 假设没有时间的字符串日期是 UTC,如果填充 0,如果不填充,则为本地?

Why does JS assume string date without time is UTC if 0 padded and local if not padded?

这很奇怪,但我相信有一个完美的解释。

我和我的团队最近在使用 java 的 LocalDate 并使用默认字符串格式 [= 将其发送回前端时发现35=],Javascript会自动创建一个日期假设字符串是UTC,所以住在ET区,它会自动减去-5小时。

很烦人,但我们明白了。

然而,当我们像这样 "YYYY-MM-DDThh:mm:ss" 将其随时间发回时,它会将其解析为本地日期。好吧,很奇怪……但它变得更奇怪了。

现在奇怪的是,如果我们发送的字符串没有日期的 0 填充 "YYYY-MM-D" 它会将其解析为本地日期。 为什么?

这是一个例子:

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)

这是为什么???

答案取决于您的浏览器实现。

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.