How to detect user's timezone?

后端 未结 6 1039
独厮守ぢ
独厮守ぢ 2020-11-22 13:00

I need to know what time zone is currently my users are in based on their IP or http header.

I got many answer regarding this issue, but i could not understood thos

6条回答
  •  醉酒成梦
    2020-11-22 14:02

    Timezone is not available in the HTTP header, but country (abbreviation) is in the ACCEPT_LANGUAGE header. It'll be something like "en-US" (US is the country code). This can be combined with the JavaScript information to get a good idea of the user's timezone.

    This is what I'm using in JS:

    function timezone() {
      var now = new Date();
      var jano = new Date(now.getFullYear(), 0, 1).getTimezoneOffset()/-60;
      var julo = new Date(now.getFullYear(), 6, 1).getTimezoneOffset()/-60;
      var tz = Math.min(jano, julo);
      if (jano != julo) tz += ((jano < julo) ? 'S' : 'W') + Math.abs(jano - julo);
      return tz;
    }
    

    This returns a string like "-6S1" for the central zone (standard time offset of -6 hours, DST active in the summer and adds 1 hour). I use a cookie to make this available to PHP. PHP searches the TZ database for zones that match this, and the country. For here (US, -6S1) there are 7 matching zones, the first is "America/Chicago".

    BTW, there are 2 zones in the database where DST adds something other than 1 hour: Lord Howe Island (10.5W0.5) and Troll Station, Antarctica (0W2).

提交回复
热议问题