admin管理员组

文章数量:1406340

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

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

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

new Date(new Date().toLocaleString())
// or
Date.parse(new Date().toLocaleString())
Share Improve this question edited May 1, 2015 at 14:36 AstroCB 12.4k20 gold badges59 silver badges74 bronze badges asked May 1, 2015 at 14:34 ChrisChris 12.3k5 gold badges22 silver badges23 bronze badges 1
  • It's because new Date accepts a string in the IETF-pliant RFC 2822 timestamp format, or ISO8601 format, it does not support random local datestrings, like those created by toLocaleString – adeneo Commented May 1, 2015 at 14:40
Add a ment  | 

2 Answers 2

Reset to default 2

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.

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

本文标签: javascriptWhy does parsing a locale date string result in an invalid dateStack Overflow