JavaScript Date: Why are these two dates different?

Here is the code from my debugger:

new Date('05-20-2015').toString()
"Wed May 20 2015 00:00:00 GMT-0500 (Central Daylight Time)"
new Date('2015-05-20').toString()
"Tue May 19 2015 19:00:00 GMT-0500 (Central Daylight Time)"

I expected the same results, but why are they different?

+4
source share
2 answers

The ISO format (ex YYYY-MM-DD is a short form) will be considered as the UTC time zone.

Other date strings will be treated as the local time zone.

MDN Source

Related

Manually set the time zone

var d1 = new Date('05-20-2015'); // local timezone

var d2 = new Date('2015-05-20'); // UTC timezone
d2.setUTCMinutes(d2.getTimezoneOffset()); // need to set to local timezone

console.log(d1.toString() === d2.toString()); // true
Run codeHide result
+1
source

I think the difference is in how the value is evaluated.

new Date('05-20-2015').toString();//parse the date using local time zone
new Date('2015-05-20').toString();//parses date as if it is in GMT

As you can see, there is a difference of 5 hours between the setpoints

Date.parse ()

, , parse() . RFC2822/IETF (RFC2822, 3.3), . ", 25 1995 13:30:00 GMT". , , , ", 25 1995 13:30:00 +0430" (4 , 30 ). ISO, ES5, UTC. UTC . RFC2822 3.3 ( ES5 ISO 8601), .

2015-05-20 ISO8601, UTC.

, , new Date('2015-05-20 GMT-0500')

+2

Source: https://habr.com/ru/post/1589112/


All Articles