Javascript date string passed to Date constructor gives strange results

Why do I get such differing results with similarly formatted date strings when creating a new date?

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) console:


    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


The lesson seems to be: IF you're going to use strings in the Date constructor, make sure it's formatted correctly (per ECMAScript standard):

YYYY-MM-DDTHH:mm:ss.sssZ

CHROME:

    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


The ECMAScript standard says in 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);

And in 15.9.4.2 it says:

    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.

...which says to me, if you don't provide that exact format, Chrome and Firefox and everyone else can interpret the date string how they deem right. (note: there is some leeway on the format, for example, the value of an absent sss field is “000”. see section 15.9.1.15 for more details)

链接地址: http://www.djcxy.com/p/18644.html

上一篇: 将日期转换为JS日期对象

下一篇: 传递给Date构造函数的Javascript日期字符串会给出奇怪的结果