简体   繁体   English

如何在PHP中将日期时间转换为用户时区

[英]How to convert a date time to a users time zone in PHP

I have a date time entered in the timezone UTC+0 and in the format 我在UTC + 0时区中以格式输入了日期时间

$curDate = date("Y-m-d");
$curTime = date("g:i a");

What I want is, detect the timezone of the visiting user. 我想要的是,检测访问用户的时区。

After that convert the date and time into his/her time zone and show the date time in their timezone. 之后,将日期和时间转换为他/她的时区,并在其时区中显示日期时间。

You could use http://ipinfodb.com/ to detect users localization and as a result users timezone, for instance: 您可以使用http://ipinfodb.com/来检测用户的本地化,从而检测用户的时区,例如:

function geoLocalization($ip, $api_key)
{
  $params = @file_get_contents("http://api.ipinfodb.com/v2/ip_query.php?key=".$api_key."&ip=".$ip."&timezone=true");
  $fields = @new SimpleXMLElement($params);
  foreach($fields as $field => $val) {
      $result[(string)$field] = (string)$val;
  }
  return $result;
}

as you get users localization you can use date_default_timezone_set to set the timezone. 当您获得用户本地化时,可以使用date_default_timezone_set设置时区。 It is good practice to let your users to overwrite this. 好的做法是让您的用户覆盖它。

You can find all timezones on this site: http://php.net/manual/en/timezones.php 您可以在此站点上找到所有时区: http : //php.net/manual/en/timezones.php

For php +5.3 you can use DateTime::createFromFormat . 对于php +5.3,您可以使用DateTime :: createFromFormat But for previous versions of php, You should use of strtotime() . 但是对于早期版本的php,您应该使用strtotime() here is a example: 这是一个例子:

$curDate = date('l, F d y h:i:s');
$curDate = strtotime($curDate);
$new = date('Y-m-d H:i:s', $curDate);
$utc_date = DateTime::createFromFormat(
    'Y-m-d G:i',
    '2011-04-27 02:45',
    new DateTimeZone('UTC')
);

$acst_date = clone $utc_date; // we don't want PHP's default pass object by reference here
$acst_date->setTimeZone(new DateTimeZone('Australia/Yancowinna'));

echo 'UTC:  ' . $utc_date->format('Y-m-d g:i A');  // UTC:  2011-04-27 2:45 AM
echo 'ACST: ' . $acst_date->format('Y-m-d g:i A'); // ACST: 2011-04-27 12:15 PM

Either force the user to provide you the timezone as the very first thing. 要么迫使用户首先向您提供时区。

Or 要么

Gets request's IPAddr, then geolocation, then tmezone. 获取请求的IPAddr,然后获取地理位置,然后获取tmezone。

The second option is dependent upon 3rd party libraries and 3rd part servers. 第二个选项取决于第三方库和第三方服务器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM