Take the date '2022-04-01' and another date '2022-05-15' for example. When I calculated their deviation in Chrome devtools, what I got is:
The result is 3801600000
. But when my friend did the same thing in another device, what he got is:
The result is 3798000000
. The difference between 3801600000
and 3798000000
is exactly one hour. What may causes this result? How can I eliminate this difference?
CodePudding user response:
You lack the zone data:
UTC datetime: new Date("2021-01-01T12:00:00Z");
UTC-4 datetime: new Date("2021-01-01T12:00:00-04:00");
CodePudding user response:
The main issue you are experiencing is because your input string is being interpreted as assigned to the local time zone, and you have different time zones on the two machines you've been testing with. One of them has a DST transition between the two dates, and the other does not - which explains your one hour difference.
The examples you show also reveal your possible time zones:
Your machine is showing 8 hours ahead of UTC (UTC 8) for both timestamps. There are several parts of the world that use UTC 8 without DST, including China, Western Australia, Irkutsk Russia, and many others. There are no places on earth that use UTC 8 in conjunction with DST.
Your friend's machine is a different story. The timestamps are showing 2 hours ahead of UTC (UTC 2) on 2022-04-01, and 3 hours ahead of UTC (UTC 3) on 2022-05-15. While many countries use those offsets (such as those that are in Eastern Europe that use EET/EEST), none of those areas have a DST transition between those two dates. See the bottom of this table of DST transitions. All of the 2/ 3 areas of the world transitioned in March. I can only conclude that your friend's machine has some non-standard time zone setting, or they are significantly behind on time zone data updates, or both. (Please reply in comments if I am incorrect on this!)
Also, your input string format, 2022-04-01 00:00:00
is not in the standard date time string format defined by the ECMAScript specification. Thus, it is not guaranteed to be parsed consistently by all browsers. Current versions of Chrome, Edge, and Firefox will interpret it as a local date and time, but the current version of Safari will fail with "Invalid Date".
If you want it interpreted as local time correctly in all browsers, you would need to specify it as
2044-04-01T00:00:00
.If you want it interpreted as UTC then specify as
2044-04-01T00:00:00Z
.If you want it interpreted with a specific time zone offset, then append that instead, as in:
2044-04-01T00:00:00 08:00
.
If you must parse the string in the original format, then don't do it using the Date
object. Either use a library (such as Luxon or date-fns), or parse it yourself with regex and/or string manipulation techniques.