传递给Date构造函数的Javascript日期字符串给出了奇怪的结果

时间:2015-07-22 19:25:07

标签: javascript date constructor

为什么在创建新日期时,使用类似格式的日期字符串会得到如此不同的结果?

CHROME (43.0.2357.134 m)console:


    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

1 个答案:

答案 0 :(得分:1)

课程似乎是: IF 您将在Date构造函数中使用字符串,确保其格式正确(每ECMAScript standard):

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部分)