📜 ⬆️ ⬇️

Date.prototype.getTimezoneOffset - the difference in return values ​​in different browsers

When implementing the task, the countdown timer encountered one “surprise”, namely, the getTimezoneOffset method, which gave it 3 hours, then 4 hours difference. This would like to share.

In this case, the error setInterval is so small that it could be neglected.
The implementation of the task itself:
(function init() { var date1 = new Date("Jan 1, 1970"), date2 = new Date("Jan 1, 1970"), timezoneOffset = new Date().getTimezoneOffset(), $days = $('.timestamp .days .number'), $hours = $('.timestamp .hours .number'), $minutes = $('.timestamp .minutes .number'); date1.setMinutes(-timezoneOffset); date2.setMinutes(-timezoneOffset); date2.setUTCSeconds(60); var timer = setInterval(function() { $days.text( parseInt(date2.getTime()/1000/60/60/24) ); $hours.text( date2.getUTCHours() ); $minutes.text( date2.getUTCMinutes() ); date2.setUTCSeconds( date2.getUTCSeconds()-1 ); if (date1.toUTCString() === date2.toUTCString()) { clearInterval(timer); } }, 1000) })() 

Soon I discovered a bug, when IE had less than an hour, but the counter displayed 1 hour, while in other browsers it was fine.
The whole problem turned out to be this:
 timezoneOffset = new Date().getTimezoneOffset(), 

So, let's try to get the time zone offsets:
 new Date('1 Jan, 1970').getTimezoneOffset(); 

We get an offset of 240 minutes;
In IE, when executing the same code, we get an offset in the time zone as early as 3 hours.
Let's see what IE returns to us in the case of a year close to the current one:
 new Date('1 Jan, 2012').getTimezoneOffset(): //-240 new Date('1 Jan, 2011').getTimezoneOffset(); //-180 

An error in the code occurred due to the fact that for the code
 new Date("Jan 1, 1970"), 

we get an offset of 3 hours, and for
 new Date().getTimezoneOffset() 

already at 4 o'clock.
I believe that this is taking into account what Russia has been doing lately - the transfer of arrows.
Which approach is correct here: IE or others?

')

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


All Articles