3

These are my two codes:

var date1 = new Date('2017-04-23');
var date2 = new Date('April 23, 2017');

console.log(date1);
console.log(date2);

this is the results:

Sat Apr 22 2017 17:00:00 GMT-0700 (PDT)
Sun Apr 23 2017 00:00:00 GMT-0700 (PDT)

why is date1 showing as the 22nd at 17:00?

Jason Bale
  • 363
  • 2
  • 7
  • 14
  • The answer I found is here: http://stackoverflow.com/questions/7556591/javascript-date-object-always-one-day-off – Jason Bale Apr 22 '17 at 18:51

1 Answers1

2

JavaScript's Date parsing behavior is somewhat unreliable. It seems that when you give it an ISO 8601 string such as `"2017-04-23" it interprets the date as being in your own timezone, but when you give it an arbitrary string, it will interpret it as a UTC date.

Since you are in the GMT-7 timezone, the 22nd at 17:00 is the 23rd at 00:00 in UTC, and when you print out a date object, it will always print out the UTC date and not the localized date.

So, in summary, both dates are getting set to the 23rd at 00:00, but in different timezones. The first is being set to Apr 23 00:00 UTC-7 and the second one is being set to Apr 23 00:00 UTC.

It might be a good idea to always explicitly set a timezone in order to avoid this ambiguity.

Pedro Castilho
  • 10,174
  • 2
  • 28
  • 39
  • 1
    You mean it's the other way round: the first string is 00:00 UTC and the second is 00:00 UTC-7. (But they both get printed in UTC-7.) Likewise your first paragraph is also the wrong way round. – David Knipe Apr 22 '17 at 19:23