Ray
Ray

Reputation: 370

Javascript new Date(str) - different parsing rules

I tried this in the Chrome JS console, with my locale time zone set as PST:

(new Date("07-15-2005"))

=> Fri Jul 15 2005 00:00:00 GMT-0700 (PDT)

(new Date("07-15-2005")).getTime();

=> 1121410800000

but....

(new Date("2005-07-15"))

=> Thu Jul 14 2005 17:00:00 GMT-0700 (PDT)

(new Date("2005-07-15")).getTime();

=> 1121385600000

I was expecting string parsing to occur in both. But I can't make out why when format YYYY-MM-DD is used, it assumes a timezone offset. It's as if I'm expressing "2005-07-15" in my local TZ, but "07-15-2005" is expressed in UTC.

Is the correct explanation?

Upvotes: 2

Views: 228

Answers (3)

Satyajit
Satyajit

Reputation: 3859

It will vary from browser to browser. The ECMA262 spec says any string which is not in YYYY-MM-DD format and is passed to the Date function, it may fall back to implementation-specific heuristics or implementation-specific date formats.

Upvotes: 0

DeadAlready
DeadAlready

Reputation: 3008

The implementation seems to be vendor specific, however looking at the documentation of date parse we see that as of 1.8.5 javascript supports both RFC2822 dates and ISO 8601 dates.

As per the Date.UTC documentation ISO 8601 dates are assumed to be in UTC time if not otherwise specified and thus the timezone difference is automatically added.

RFC2822 dates seem to be assumed as local times and as such are not modified.

Upvotes: 1

Niels Abildgaard
Niels Abildgaard

Reputation: 2980

I cannot seem to replicate your results, but the results seem to differ from browser to browser.

See: http://jsfiddle.net/f7DMV/

In Firefox and Opera, I get only the middle line parsing correctly, the others are Invalid Dates.

In Chrome, both the first and the second line parse correctly (and don't differ), but the last one is still Invalid.

Upvotes: 0

Related Questions