2

I have to admit, I've never quite understood Javascript date objects, but now I'm really confused with how they are constructed. Consider the following:

var x = new Date('2017-01-01');
var y = new Date('2017-01-01 00:00:00');

// x
// Sat Dec 31 2016 19:00:00 GMT-0500 (Eastern Standard Time)
 
// y
// Sun Jan 01 2017 00:00:00 GMT-0500 (Eastern Standard Time)
  
console.log(x);
console.log(y);

How or why are x and y producing different values? From what I'm used to (C#, SQL, common sense, etc.), 2017-01-01 is the same as 2017-01-01 00:00:00. Can someone enlighten me on why the resulting Date values are not the same?

j08691
  • 204,283
  • 31
  • 260
  • 272
jtate
  • 2,612
  • 7
  • 25
  • 35
  • 3
    This may help: http://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results –  May 12 '17 at 15:12
  • Could it be a TZ issue (although it makes no sense still)? I live in UTC timezone and both examples result in `2017-01-01T00:00:00.000Z` on my end... – errata May 12 '17 at 15:13
  • @jtate—the built-in Date lacks a decent parser and formatter, but other than that, Dates are fine. – RobG May 12 '17 at 22:09

2 Answers2

1

As MDN documentation notes:

Because of the variances in parsing of date strings, it is recommended to always manually parse strings as results are inconsistent, especially across different ECMAScript implementations where strings like "2015-10-12 12:00:00" may be parsed to as NaN, UTC or local timezone. (emphasis mine)

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
  • why are there "variances in parsing of date strings"? I'm more interested in the "why" aspect of this, because it's very confusing as to why it's not consistent. – jtate May 12 '17 at 16:07
1

From mdn https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.

Seems if you fail to provide a time it converts to UTC. Which if you're eastern is 5 hours ahead. hope that helps.

dgeare
  • 2,618
  • 5
  • 18
  • 28