Why does parsing a locale date string result in an

2019-06-26 09:35发布

Can someone explain why the following snippets result in an invalid date object?

new Date(new Date().toLocaleString())
// or
Date.parse(new Date().toLocaleString())

2条回答
Melony?
2楼-- · 2019-06-26 09:39

This is expressly permitted by the ES5 specification's definition of Date.parse (emphasis mine):

...all of the following expressions should produce the same numeric value in that implementation, if all the properties referenced have their initial values:

x.valueOf()
Date.parse(x.toString())
Date.parse(x.toUTCString())
Date.parse(x.toISOString())

However, the expression

Date.parse(x.toLocaleString())

is not required to produce the same Number value as the preceding three expressions and, in general, the value produced by Date.parse is implementation-dependent when given any String value that does not conform to the Date Time String Format (15.9.1.15) and that could not be produced in that implementation by the toString or toUTCString method.

Since toLocaleString is not required to produce a string conformant to the Date Time String Format YYYY-MM-DDTHH:mm:ss.sssZ, it is allowable for its output not to be parsed correctly by Date.parse.

查看更多
趁早两清
3楼-- · 2019-06-26 09:50

new Date().toLocaleString() returns the current date in a format new Date() can't parse, resulting in unexpected dates.

查看更多
登录 后发表回答