为什么 Date.parse 给出不正确的结果? [英] Why does Date.parse give incorrect results?
问题描述
new Date(Date.parse("Jul 8, 2005"));
输出:
2005 年 7 月 8 日星期五 00:00:00 GMT-0700(太平洋标准时间)
Output:
Fri Jul 08 2005 00:00:00 GMT-0700 (PST)
new Date(Date.parse("2005-07-08"));
输出:
2005 年 7 月 7 日星期四 17:00:00 GMT-0700(太平洋标准时间)
Output:
Thu Jul 07 2005 17:00:00 GMT-0700 (PST)
为什么第二次解析不正确?
Why is the second parse incorrect?
推荐答案
直到第 5 版规范出来,Date.parse
方法完全实现依赖(new Date(string)
等价于Date.parse(string)
除外后者返回一个数字而不是一个 Date
).在第 5 版规范中添加了要求以支持 简化(稍微不正确) ISO-8601(另见 JavaScript 中的有效日期时间字符串是什么?).但除此之外,没有要求 Date.parse
/new Date(string)
应该接受什么,除了他们必须接受任何 Date#toString
输出(不说那是什么).
Until the 5th edition spec came out, the Date.parse
method was completely implementation dependent (new Date(string)
is equivalent to Date.parse(string)
except the latter returns a number rather than a Date
). In the 5th edition spec the requirement was added to support a simplified (and slightly incorrect) ISO-8601 (also see What are valid Date Time Strings in JavaScript?). But other than that, there was no requirement for what Date.parse
/ new Date(string)
should accept other than that they had to accept whatever Date#toString
output (without saying what that was).
从 ECMAScript 2017(第 8 版)开始,实现需要解析 Date#toString
和 Date#toUTCString
的输出,但这些字符串的格式不是指定.
As of ECMAScript 2017 (edition 8), implementations were required to parse their output for Date#toString
and Date#toUTCString
, but the format of those strings was not specified.
从 ECMAScript 2019(第 9 版)开始,的格式Date#toString
和 Date#toUTCString
,已被指定为(分别):
As of ECMAScript 2019 (edition 9) the format for Date#toString
and Date#toUTCString
, have been specified as (respectively):
- ddd MMM DD YYYY HH:mm:ss ZZ [(时区名称)]
例如2018 年 7 月 10 日星期二 18:39:58 GMT+0530 (IST) - ddd, DD MMM YYYY HH:mm:ss Z
例如格林威治标准时间 2018 年 7 月 10 日,星期二 13:09:58
提供另外 2 种格式,Date.parse
应该在新的实现中可靠地解析这些格式(注意支持并不普遍,不合规的实现将继续使用一段时间).
providing 2 more formats that Date.parse
should parse reliably in new implementations (noting that support is not ubiquitous and non–compliant implementations will remain in use for some time).
我建议手动解析日期字符串和 日期构造函数 与年、月和日参数一起使用以避免歧义:
I would recommend that date strings are parsed manually and the Date constructor used with year, month and day arguments to avoid ambiguity:
// parse a date in yyyy-mm-dd format
function parseDate(input) {
let parts = input.split('-');
// new Date(year, month [, day [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[0], parts[1]-1, parts[2]); // Note: months are 0-based
}
这篇关于为什么 Date.parse 给出不正确的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!