为什么解析语言环境日期字符串导致无效日期? [英] Why does parsing a locale date string result in an invalid date?

查看:71
本文介绍了为什么解析语言环境日期字符串导致无效日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释为什么以下代码段会导致无效的日期对象吗?

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

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


推荐答案

ES5规范的定义 Date.parse (强调我的):

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())

然而,表达式

Date.parse(x.toLocaleString())

不需要生成t与前三个表达式相同的数值,一般来说, Date.parse 生成的值在给定任何String值时依赖于实现不符合日期时间字符串格式 15.9.1.15 )并且无法通过 toString toUTCString 方法在该实现中生成。

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.

由于 toLocaleString 不需要生成符合日期的字符串时间字符串格式 YYYY-MM-DDTHH:mm:ss.sssZ ,允许 Date.parse <正确解析其输出/ code>。

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.

这篇关于为什么解析语言环境日期字符串导致无效日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆