M.Octavio
M.Octavio

Reputation: 1808

Javascript new Date

There is a funny thing in JavaScript, not a big deal but I would like to know, why is this happening.

If you do this:

new Date('2014-6-12')

you'll get:

Thu Jun 12 2014 00:00:00 GMT-0600 (Central America Standard Time)

which is totally fine but if you do the same using the day with the format 'dd' instead of 'd' like this:

new Date('2014-06-12')

you'll get a different result:

Wed Jun 11 2014 18:00:00 GMT-0600 (Central America Standard Time)

Upvotes: 3

Views: 110

Answers (1)

RobG
RobG

Reputation: 147363

Because '2014-06-12' appears to be an ISO 8601 date format without a time zone, so it's treated as UTC (per ES5) by most browsers but not all. '2014-6-12' is seen as some other format so is treated as local.

ES6 will change that so that ISO 8601 dates without a timezone should be treated as local (per ISO 8601). Confused? ECMAScript 2015 was originally interpreted as treating ISO 8601 date only forms as local, but that was changed to treat them as UTC. All subsequent versions of ECMAScript also treat them as UTC (which is inconsistent with ISO 8601).

So do not parse strings with the built-in parser (i.e. new Date(string) or Date.parse(string)), its behaviour is inconsistent across browsers and not necessarily standards compliant. Use a library, or write your own simple parser:

// Expect year-month-day, treat as local date
function parseYMD(s) {
  var b = s.split(/\D+/);
  return new Date(b[0], --b[1], b[2]);
}

The above is simple but does not test if the date is valid, to do that takes an extra line:

// Expect year-month-day, treat as local date
function parseYMD(s) {
  var b = s.split(/\D+/);
  var d = new Date(b[0], --b[1], b[2]);
  return d && d.getFullYear() == b[0] && d.getDate() == b[2]? d : NaN;
}

Also see Why does Date.parse give incorrect results?

Upvotes: 4

Related Questions