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 bytoLocaleString
– adeneo Commented May 1, 2015 at 14:40
2 Answers
Reset to default 2This 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 thetoString
ortoUTCString
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
版权声明:本文标题:javascript - Why does parsing a locale date string result in an invalid date? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745004618a2637183.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论