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?