Javascript date string passed to Date constructor gives strange results

Why am I getting such different 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

+3


source to share


1 answer


The lesson looks like this: IF . You are going to use strings in the Date constructor, make sure it is formatted correctly (per ECMAScript standard ):

YYYY-MM-DDTHH:mm:ss.sssZ

      

CHROMIUM:

    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: 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 15.9.4.2 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 tells me if you don't give the exact format, Chrome and Firefox and everyone else can interpret the date string as they think is correct. (note: there is some format freedom, for example the value of the missing sss field is "000". see section 15.9.1.15 for more details)

+1


source







All Articles