为什么Date.parse会给出不正确的结果? [英] Why does Date.parse give incorrect results?
问题描述
new Date(Date.parse("Jul 8, 2005"));
输出:
Fri Jul 08 2005 00:00:00 GMT-0700(PST)
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(PST)
Output:
Thu Jul 07 2005 17:00:00 GMT-0700 (PST)
为什么第二个解析不正确?
Why is the second parse incorrect?
推荐答案
直到第5版规格出来, Date.parse
方法完全依赖于实现(新的日期(字符串)
相当于 Date.parse(string)
,除了后者返回一个数字而不是 Date
)。在第5版规范中,添加了要求,以支持简化(稍微不正确) ISO-8601 ,但除此之外,对于 Date.parse $ c 否 $ c> /
new Date(string)
应该接受,除了他们不得不接受任何 Date#toString
output不用说这是什么)。
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, 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).
我建议您手动解析日期字符串,并使用 Date构造函数与年,月和日参数以避免歧义:
I would recommend you to parse your date string manually, and use the Date constructor with the year, month and day arguments to avoid ambiguity:
// parse a date in yyyy-mm-dd format
function parseDate(input) {
var 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屋!