最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Date.getTimezoneOffset inverted? - Stack Overflow

programmeradmin1浏览0评论

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.
发布评论

评论列表(0)

  1. 暂无评论