Inconsistent getTimezoneOffset results
getTimezoneOffset
returns the offset within a specific point in time represented by the object Date
it is invoked using the timezone setting of the computer on which it is 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 get the current offset.
The value returned from getTimezoneOffset
is in terms of minutes west of UTC, compared to the more common offsets returned in a format [+/-]HH:mm
that are east of UTC. So the timezone you gave alternates between UTC + 1 and UTC + 2. I am assuming that the computer that gave this result was in one of the zones that use CET, although it could be one of several others.
Also, when you pass an offset as part of an ISO8601 formatted string, that offset is actually taken into account - but only during parsing. The offset is applied and the object is Date
held inside the UTC timestamp. Then it forgets about the offset you provided. In the output, some functions will explicitly use UTC, but most will convert to the local timezone before fixing their result.
You also asked how to get the offset of a datetime string using moment.js . Yes, it's pretty 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"
source to share
This is due to Daylight Saving Time . For your time zone, June 11th is in UTC + 2 and March 10th is in UTC + 1:
// when in DST (since it June)
new Date("2015-06-11T00:00:00Z").getTimezoneOffset(); // -120
// when not in DST
new Date("2015-03-10T15:48:05+01:00").getTimezoneOffset(); // -60
For me, since I am in the Eastern Time Zone, the following will happen:
// when in EST
new Date("2015-03-01T00:00:00Z").getTimezoneOffset(); // 300
// when in EDT
new Date("2015-06-01T00:00:00Z").getTimezoneOffset(); // 240
source to share