javascript 在不同的浏览器中表现不同
javascript behaves differently in different browsers
我正在做一个需要处理很多 "dates" 的项目。我注意到有时 javascript 在不同的浏览器中表现不同:
代码:
new Date("Mar 30, 2017".replace(',', '').replace(/ /g, '/'))
我知道我不需要使用 replace
来创建日期,但是这段代码给了我与 Chrome 和 Safari 不同的有趣结果。
而我 运行:
"Mar 30, 2017".replace(',', '').replace(/ /g, '/')
Chrome 和 Safari 都会给我:"Mar/30/2017"
。但是当我尝试将结果变成 Date
对象时,有趣的结果将是:
Chrome: Thu Mar 30 2017 00:00:00 GMT-0700 (PDT)
Firefox: Date 2017-03-30T07:00:00.000Z
Safari: Invalid Date
我已经检查了两个浏览器的 Javascript 版本,它们使用的是相同的版本 (1.7)。谁能解释为什么 Chrome 在这方面的行为与 Safari 不同?
更新
我知道 "Mar/30/2017"
不是有效的日期格式。但我的问题是 为什么 javascript 在不同的浏览器中表现不同 。对于那些抱怨我的日期格式的答案。请先阅读问题再回答。我会接受@Felix Kling 的回答,同样感谢所有的回答。
Can anyone explain why Chrome behaves differently than Safari in this regard?
specification 表示处理未知日期格式取决于实现:
[...] The String may be interpreted as a local time, a UTC time, or a time in some other time zone, depending on the contents of the String. The function first attempts to parse the format of the String according to the rules (including extended years) called out in Date Time String Format (20.3.1.16). If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats. [...]
Safari 和 Chrome 使用不同的 JavaScript 引擎,因此在这种情况下它们的行为可能(并且确实)不同。
我正在做一个需要处理很多 "dates" 的项目。我注意到有时 javascript 在不同的浏览器中表现不同:
代码:
new Date("Mar 30, 2017".replace(',', '').replace(/ /g, '/'))
我知道我不需要使用 replace
来创建日期,但是这段代码给了我与 Chrome 和 Safari 不同的有趣结果。
而我 运行:
"Mar 30, 2017".replace(',', '').replace(/ /g, '/')
Chrome 和 Safari 都会给我:"Mar/30/2017"
。但是当我尝试将结果变成 Date
对象时,有趣的结果将是:
Chrome: Thu Mar 30 2017 00:00:00 GMT-0700 (PDT)
Firefox: Date 2017-03-30T07:00:00.000Z
Safari: Invalid Date
我已经检查了两个浏览器的 Javascript 版本,它们使用的是相同的版本 (1.7)。谁能解释为什么 Chrome 在这方面的行为与 Safari 不同?
更新
我知道 "Mar/30/2017"
不是有效的日期格式。但我的问题是 为什么 javascript 在不同的浏览器中表现不同 。对于那些抱怨我的日期格式的答案。请先阅读问题再回答。我会接受@Felix Kling 的回答,同样感谢所有的回答。
Can anyone explain why Chrome behaves differently than Safari in this regard?
specification 表示处理未知日期格式取决于实现:
[...] The String may be interpreted as a local time, a UTC time, or a time in some other time zone, depending on the contents of the String. The function first attempts to parse the format of the String according to the rules (including extended years) called out in Date Time String Format (20.3.1.16). If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats. [...]
Safari 和 Chrome 使用不同的 JavaScript 引擎,因此在这种情况下它们的行为可能(并且确实)不同。