admin管理员组

文章数量:1323200

I have a JSON response from my server giving me UTC Unix timestamps in seconds. I'm parsing that into JavaScript dates that will be used in a chart (displaying the time in the user's locale).

I obviously have to coax the timestamp I have (in UTC) into the browser's locale, so I wrote a function that creates a new Date in the browser's locale, calls getTimezoneOffset() on it to get the "offset in minutes" in the current locale, as per the MDN, converts both to milliseconds, and returns the sum. Now I have a JavaScript friendly Unix timestamp in the user's locale.

However, I don't.

as it turns out, (new Date()).getTimezoneOffset() returns (positive) 300 in GMT-5 and -120 in GMT+2. Why is the offset inverted? I would have expected the offset to match the sign of the timezone - ie: I need to subtract 300 minutes to get to GMT-5, and ADD 120 minutes to get to GMT+2. Instead, I have to subtract the values that are returned by getTimezoneOffset

I have a JSON response from my server giving me UTC Unix timestamps in seconds. I'm parsing that into JavaScript dates that will be used in a chart (displaying the time in the user's locale).

I obviously have to coax the timestamp I have (in UTC) into the browser's locale, so I wrote a function that creates a new Date in the browser's locale, calls getTimezoneOffset() on it to get the "offset in minutes" in the current locale, as per the MDN, converts both to milliseconds, and returns the sum. Now I have a JavaScript friendly Unix timestamp in the user's locale.

However, I don't.

as it turns out, (new Date()).getTimezoneOffset() returns (positive) 300 in GMT-5 and -120 in GMT+2. Why is the offset inverted? I would have expected the offset to match the sign of the timezone - ie: I need to subtract 300 minutes to get to GMT-5, and ADD 120 minutes to get to GMT+2. Instead, I have to subtract the values that are returned by getTimezoneOffset

Share Improve this question asked Feb 3, 2013 at 4:23 Thomas JonesThomas Jones 4,96230 silver badges35 bronze badges 2
  • See the description here.This means that the offset is positive if the local timezone is behind UTC and negative if it is ahead. – Jashwant Commented Feb 3, 2013 at 4:35
  • so if I'd actually clicked through to the method...... facepalm – Thomas Jones Commented Feb 3, 2013 at 4:37
Add a ment  | 

1 Answer 1

Reset to default 9

Nope.

The spec (§15.9.5.26) says:

15.9.5.26 Date.prototype.getTimezoneOffset ( )

Returns the difference between local time and UTC time in minutes.

  1. Let t be this time value.
  2. If t is NaN, return NaN.
  3. Return (t − LocalTime(t)) / msPerMinute.

本文标签: javascriptDategetTimezoneOffset invertedStack Overflow