Why does Javascript convert time differently?

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);

      

these are the results:

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

      

why date1

is it displayed as 22nd at 17:00?

+3


source to share


1 answer


JavaScript Date

parsing behavior is somewhat unreliable. It looks like when you give it an ISO 8601 string like "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 GMT-7 timezone, 22nd at 17:00 - 23rd at 00:00 in UTC, and when you print a date object, it will always print the UTC date, not the localized date.



So, in the end, both dates are set to 23rd at 00:00, but in different time zones. The first is set to 23 April 00:00 UTC-7, and the second is set to 23 April 00:00 UTC.

It may be a good idea to always set the time zone explicitly to avoid this ambiguity.

+2


source







All Articles