How to detect user's timezone?

后端 未结 6 1108
独厮守ぢ
独厮守ぢ 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 13:54

    Dependencies:

    1. http://www.maxmind.com/download/geoip/api/php/php-latest.tar.gz
    2. http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz

      //Get remote IP
      $ip = $_SERVER['REMOTE_ADDR'];
      
      //Open GeoIP database and query our IP
      $gi = geoip_open("GeoLiteCity.dat", GEOIP_STANDARD);
      $record = geoip_record_by_addr($gi, $ip);
      
      //If we for some reason didnt find data about the IP, default to a preset location.
      if(!isset($record)) {
          $record = new geoiprecord();
          $record->latitude = 59.2;
          $record->longitude = 17.8167;
          $record->country_code = 'SE';
          $record->region = 26;
      }
      
      //Calculate the timezone and local time
      try {
          //Create timezone
          $user_timezone = new DateTimeZone(get_time_zone($record->country_code, ($record->region!='') ? $record->region : 0));
      
          //Create local time
          $user_localtime = new DateTime("now", $user_timezone);
          $user_timezone_offset = $user_localtime->getOffset();        
      }
      //Timezone and/or local time detection failed
      catch(Exception $e) {
          $user_timezone_offset = 7200;
          $user_localtime = new DateTime("now");
      }
      
      echo 'User local time: ' . $user_localtime->format('H:i:s') . '
      '; echo 'Timezone GMT offset: ' . $user_timezone_offset . '
      ';

    citation: SGet visitor local time, sunrise and sunset time by IP with MaxMind GeoIP and PHP by Stanislav Khromov

提交回复
热议问题