get client's GMT offset in javascript

前端 未结 1 1341
囚心锁ツ
囚心锁ツ 2021-01-15 09:31

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 calculat

相关标签:
1条回答
  • 2021-01-15 10:04

    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.

    0 讨论(0)
提交回复
热议问题