Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Javascript convert times differently? [duplicate]

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?

like image 520
Jason Bale Avatar asked Apr 14 '26 20:04

Jason Bale


1 Answers

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.

like image 179
Pedro Castilho Avatar answered Apr 16 '26 08:04

Pedro Castilho



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!