Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inconsistent getTimezoneOffset results

The documentation seems to suggest getTimezoneOffset() always returns the offset of the current locale, irregardless of the date object. But I'm getting inconsistent results that I can't understand.

new Date().getTimezoneOffset()                             // -120
new Date("2015-03-10T15:48:05+01:00").getTimezoneOffset()  // -60
new Date("2015-03-10T15:48:05-04:00").getTimezoneOffset()  // -60

Also, is there a better way to get the timezone off a datetime string (maybe with moment.js)?

like image 974
maged Avatar asked Mar 15 '23 18:03

maged


1 Answers

getTimezoneOffset returns the offset for the specific moment in time represented by the Date object it is called on, using the time zone setting of the computer that it executing the code.

Since many time zones change their offset for daylight saving time, it is perfectly normal for the value to differ for different dates and times. When you call it on new Date(), you're getting the current offset.

The value returned from getTimezoneOffset is in terms of minutes west of UTC, as compared to the more common offsets returned in [+/-]HH:mm format, which are east of UTC. Therefore, the time zone you gave alternates between UTC+1, and UTC+2. My guess is the computer that gave this output was in one of the zones that uses Central European Time - though it could be one of several others.

Also, when you pass in an offset as part of an ISO8601 formatted string, that offset is indeed taken into account - but only during parsing. The offset is applied, and the Date object holds on to the UTC timestamp internally. It then forgets anything about the offset you supplied. On output, some of the functions will explicitly use UTC, but most of them will convert to the local time zone before emitting their result.

You also asked about how to get the offset of a datetime string using moment.js. Yes, that is quite simple:

// Create a moment object.
// Use the parseZone function to retain the zone provided.
var m = moment.parseZone('2015-03-10T15:48:05-04:00');

// get the offset in minutes EAST of UTC (opposite of getTimezoneOffset)
var offset = m.utcOffset(); // -240

// alternatively, get it as a string in [+/-]HH:mm format
var offsetString = m.format("Z");  // "-04:00"
like image 120
Matt Johnson-Pint Avatar answered Mar 19 '23 16:03

Matt Johnson-Pint