get client's GMT offset in javascript

て烟熏妆下的殇ゞ 提交于 2020-07-15 08:53:46

问题


how can I get the GMT offset in javascript of the client?

new Date().getTimezoneOffset(); returns the difference from UTC. Is there a way I can calculate the GMT offset from that?

By GMT offset, I mean as in -5 for eastern standard time.


回答1:


new Date().getTimezoneOffset(); returns the difference from UTC. Is there a way I can calculate the GMT offset from that?

The timezone offset is the difference from GMT in minutes (see ECMA-262 §15.9.5.26). The sign is the reverse of ISO 8601, but it's easily converted to hours and minutes with a more standard sign:

function getTimezoneOffset() {
  function z(n){return (n<10? '0' : '') + n}
  var offset = new Date().getTimezoneOffset();
  var sign = offset < 0? '+' : '-';
  offset = Math.abs(offset);
  return sign + z(offset/60 | 0) + z(offset%60);
}

getTimezoneOffset() // +0800 for UTC/GMT + 8hrs

If you want to determine the IANA timezone designation, you can try pellepim jstimezonedetect, however it works by guessing based on the offset for two dates and may not be correct.



来源:https://stackoverflow.com/questions/24500375/get-clients-gmt-offset-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!