Why does parsing a locale date string result in an invalid date?

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

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

      

+3


source to share


2 answers


This is explicitly allowed by the ES5 spec definitionDate.parse

(emphasis mine):

... all of the following expressions should result in the same numeric value in this implementation if all property references 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 create the same number value as in the previous three expressions and generally the value generated Date.parse

is implementation dependent if any String value is given that does not conform to the date time string format
( 15.9.1.15 ) and this could not be created in this implementation with toString

or toUTCString

.



Since it is toLocaleString

not required to generate a string that conforms to the date time string format YYYY-MM-DDTHH:mm:ss.sssZ

, it is acceptable that its result is not parsed correctly with Date.parse

.

+1


source


new Date().toLocaleString()

returns the current date in a format new Date()

that cannot be parsed, resulting in unexpected dates.



+1


source







All Articles