传递给Date构造函数的Javascript日期字符串会给出奇怪的结果
创建新日期时,为什么我会在格式相同的日期字符串中得到不同的结果?
CHROME (43.0.2357.134米)控制台:
new Date('2014-12-25') Wed Dec 24 2014 17:00:00 GMT-0700 (Mountain Standard Time) [Chrome assumes Z with 00:00 (utc) and returns that local time] new Date('2014-1-25') Sat Jan 25 2014 00:00:00 GMT-0700 (Mountain Standard Time) [What?! exact same format (I thought) but returns 25 instead of 24....see next...] new Date('2014-01-25') Fri Jan 24 2014 17:00:00 GMT-0700 (Mountain Standard Time) [...oh, the leading 0 makes it use the logic it used in the first example] new Date('2014/12/25') Thu Dec 25 2014 00:00:00 GMT-0700 (Mountain Standard Time) [using / instead of - results in what I believe most would expect(?): a local time on the same date specified]
FIREFOX (39.0)控制台:
new Date('2014-12-25') Date 2014-12-25T00:00:00.000Z [different from Chrome] new Date('2014-1-25') Invalid Date [not recognized in Firefox, unlike Chrome] new Date('2014-01-25') Date 2014-01-25T00:00:00.000Z [different from Chrome] new Date('2014/12/25') Date 2014-12-25T07:00:00.000Z
该课程似乎是: 如果您要在Date构造函数中使用字符串,请确保它的格式正确(按照ECMAScript标准):
YYYY-MM-DDTHH:mm:ss.sssZ
铬:
new Date('2014-12-25T00:00:00.000-07:00') Thu Dec 25 2014 00:00:00 GMT-0700 (Mountain Standard Time)
FIREFOX:
new Date('2014-12-25T00:00:00.000-07:00') Date 2014-12-25T07:00:00.000Z
ECMAScript标准在15.9.3.2中说过
If Type(v) is String, then
Parse v as a date, in exactly the same manner as for the parse method (15.9.4.2);
它在15.9.4.2中说:
The function first attempts to parse the format of the String according to the rules called out in Date Time String Format (15.9.1.15). If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats.
...对我说,如果你没有提供确切的格式,Chrome和Firefox以及其他人都可以解释日期字符串他们认为是正确的。 (注意:格式有一些余地,例如缺席sss字段的值是“000”,更多细节请参见15.9.1.15节)
链接地址: http://www.djcxy.com/p/18643.html上一篇: Javascript date string passed to Date constructor gives strange results
下一篇: java.text.Parseexception, unparseble date at position 0? Android