Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript new Date

Tags:

javascript

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)
like image 955
M.Octavio Avatar asked Mar 21 '26 04:03

M.Octavio


1 Answers

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?

like image 183
RobG Avatar answered Mar 22 '26 17:03

RobG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!