Determine a user's timezone

前端 未结 25 3296
刺人心
刺人心 2020-11-21 07:12

Is there a standard way for a web server to be able to determine a user\'s timezone within a web page?

Perhaps from an HTTP header or part of the user-agent

25条回答
  •  后悔当初
    2020-11-21 07:29

    Getting a valid TZ Database timezone name in PHP is a two-step process:

    1. With JavaScript, get timezone offset in minutes through getTimezoneOffset. This offset will be positive if the local timezone is behind UTC and negative if it is ahead. So you must add an opposite sign to the offset.

      var timezone_offset_minutes = new Date().getTimezoneOffset();
      timezone_offset_minutes = timezone_offset_minutes == 0 ? 0 : -timezone_offset_minutes;
      

      Pass this offset to PHP.

    2. In PHP convert this offset into a valid timezone name with timezone_name_from_abbr function.

      // Just an example.
      $timezone_offset_minutes = -360;  // $_GET['timezone_offset_minutes']
      
      // Convert minutes to seconds
      $timezone_name = timezone_name_from_abbr("", $timezone_offset_minutes*60, false);
      
      // America/Chicago
      echo $timezone_name;

    I've written a blog post on it: How to Detect User Timezone in PHP. It also contains a demo.

提交回复
热议问题