将UTC偏移量转换为时区或日期

时间:2012-08-05 22:46:41

标签: php geolocation timezone timezone-offset

为你搔痒。

我从IPInfoDB的API获取地理IP数据,并返回UTC 的时区偏移,包括 DST(如果当前已反映)。

例如,我住在EST(-5),目前它是DST,因此geo IP API返回(-04:00)作为偏移量。

这很好,因为DST是一个令人头疼的问题。但令我惊讶的是,它引起了另一次头痛。

我在PHP中加载这些数据,通过AJAX传递给应用程序。我想在应用程序上获得IP地址的实时本地时间。

我有完美的设置,但是我疯狂地想弄清楚如何设置PHP时区以匹配偏移量,这样我就可以抓住当前小时date('H');和分钟date('i');来传递给AJAX。

我不确定是否有一个特定的功能可以根据该偏移给我当前的小时和分钟,或者是否有实际的方法根据偏移量设置时区(如果是的话,已经应用了DST)实际上。)

我一直在搜索和搜索Google以找到答案,但由于已经应用了DST,我正在做的更具体。

我在PHP.net上发现了一个似乎可以解决问题的功能(它适用于我的时区并返回正确的时间),但对于其他时区如PST,它比它应该返回的时间晚1小时偏移是正确的(-07:00与DST)。

从函数返回的时区是Chile/EasterIsland,我有一种感觉是原因。如果可以的话,我会让这只适用于美国,但我确实需要它在世界范围内。

这是我现在的功能。请原谅极其凌乱的代码。在过去的几个小时里,我一直在玩弄很多东西试图找到解决方案。

大多数功能都是在网上找到的。

function offsetToTZ($offset) {
switch((string) $offset) {
    case '-04:30' : return 'America/Caracas'; break;
    case '-03:30' : return 'Canada/Newfoundland'; break;
    case '+03:30' : return 'Asia/Tehran'; break;
    case '+04:30' : return 'Asia/Kabul'; break;
    case '+05:30' : return 'Asia/Kolkata'; break;
    case '+05:45' : return 'Asia/Kathmandu'; break;
    case '+09:30' : return 'Australia/Darwin'; break;
}
$offset = (int) str_replace(array('0',0,':00',00,'30',30,'45',45,':','+'),'', (string) $offset);

$offset = $offset*60*60;
$abbrarray = timezone_abbreviations_list(); 
foreach ($abbrarray as $abbr) { 
    foreach($abbr as $city) { 
        if($city['offset'] == $offset) { 
            return $city['timezone_id'];
        }
    }
}
return false; 
}

我为那些:30:45的某些时区添加了开关/案例。可能有一种方法可以在不需要开关/盒的情况下包含它。

注意:偏移量始终从地理IP API返回+00:00-00:00

我会感谢任何帮助或指向正确的方向。我不是PHP的新手,但偏移对我来说是一个新故事。谢谢!

8 个答案:

答案 0 :(得分:45)

通过将偏移量转换为秒并将其传递给timezone_name_from_abbr,可以非常简单地完成:

<?php
$offset = '-7:00';

// Calculate seconds from offset
list($hours, $minutes) = explode(':', $offset);
$seconds = $hours * 60 * 60 + $minutes * 60;
// Get timezone name from seconds
$tz = timezone_name_from_abbr('', $seconds, 1);
// Workaround for bug #44780
if($tz === false) $tz = timezone_name_from_abbr('', $seconds, 0);
// Set timezone
date_default_timezone_set($tz);

echo $tz . ': ' . date('r');

Demo

timezone_name_from_abbr的第三个参数控制是否调整夏令时。

Bug #44780

  

timezone_name_from_abbr()将在某个时区返回false   偏移。特别是 - 夏威夷,其GMT偏移为-10,-36000   秒。

参考文献:

答案 1 :(得分:4)

date_default_timezone_set('UTC');

$timezones = array();
foreach (DateTimeZone::listAbbreviations() as $key => $array)
{
    $timezones = array_merge($timezones, $array);
}

$utc                = new DateTimeZone('UTC');
$timezone_offset    = '+02:00'; # 2H
$sign               = substr($timezone_offset, 0, 1) == '+'? '': '-';
$offset             = substr($timezone_offset, 1, 2) . 'H' . substr($timezone_offset, 4, 2) . 'M';

$operation = $sign == ''? 'add': 'sub';

$start  = new DateTime('', $utc);
$date   = new DateTime('', $utc);

$date->{$operation}(new DateInterval("PT{$offset}"));

$offset = $start->diff($date)->format('%r') . ($start->diff($date)->h * 3600 + $start->diff($date)->m * 60 + $start->diff($date)->s); # 7200 (2H)

echo $offset, PHP_EOL;
echo $date->format('Y-m-d H:i:s'), PHP_EOL;

foreach($timezones as $timezone)
{
    if($timezone['offset'] == $offset)
    {
        echo $timezone['timezone_id'], PHP_EOL;
    }
}

我可能在某些方面误解了你,但我希望它有所帮助,如果你可以更具体,我可能会更有帮助。

对于智利我得到:

-25200 (-7h)
2012-08-07 18:05:24 (current time 2012-08-08 01:05:24)
Chile/EasterIsland

上述示例的输出:

7200
2012-08-08 02:49:56
Europe/London
Europe/Belfast
Europe/Gibraltar
Europe/Guernsey
Europe/Isle_of_Man
Europe/Jersey
GB
Africa/Khartoum
Africa/Blantyre
Africa/Bujumbura
Africa/Gaborone
Africa/Harare
Africa/Kigali
Africa/Lubumbashi
Africa/Lusaka
Africa/Maputo
Africa/Windhoek
Europe/Berlin
Africa/Algiers
Africa/Ceuta
Africa/Tripoli
Africa/Tunis
Arctic/Longyearbyen
Atlantic/Jan_Mayen
CET
Europe/Amsterdam
Europe/Andorra
Europe/Athens
Europe/Belgrade
Europe/Bratislava
Europe/Brussels
Europe/Budapest
Europe/Chisinau
Europe/Copenhagen
Europe/Gibraltar
Europe/Kaliningrad
Europe/Kiev
Europe/Lisbon
Europe/Ljubljana
Europe/Luxembourg
Europe/Madrid
Europe/Malta
Europe/Minsk
Europe/Monaco
Europe/Oslo
Europe/Paris
Europe/Podgorica
Europe/Prague
Europe/Riga
Europe/Rome
Europe/San_Marino
Europe/Sarajevo
Europe/Simferopol
Europe/Skopje
Europe/Sofia
Europe/Stockholm
Europe/Tallinn
Europe/Tirane
Europe/Tiraspol
Europe/Uzhgorod
Europe/Vaduz
Europe/Vatican
Europe/Vienna
Europe/Vilnius
Europe/Warsaw
Europe/Zagreb
Europe/Zaporozhye
Europe/Zurich
WET
Europe/Kaliningrad
Europe/Helsinki
Africa/Cairo
Africa/Tripoli
Asia/Amman
Asia/Beirut
Asia/Damascus
Asia/Gaza
Asia/Istanbul
Asia/Nicosia
EET
Europe/Athens
Europe/Bucharest
Europe/Chisinau
Europe/Istanbul
Europe/Kaliningrad
Europe/Kiev
Europe/Mariehamn
Europe/Minsk
Europe/Moscow
Europe/Nicosia
Europe/Riga
Europe/Simferopol
Europe/Sofia
Europe/Tallinn
Europe/Tiraspol
Europe/Uzhgorod
Europe/Vilnius
Europe/Warsaw
Europe/Zaporozhye
Asia/Jerusalem
Asia/Gaza
Asia/Tel_Aviv
MET
Africa/Johannesburg
Africa/Maseru
Africa/Mbabane
Africa/Windhoek
Africa/Windhoek
Africa/Ndjamena
Europe/Lisbon
Europe/Madrid
Europe/Monaco
Europe/Paris
WET
Europe/Luxembourg

指出了我的时区。

答案 2 :(得分:3)

$UTC_offset = '+03:00';
$date       = new \DateTime('now', 'UTC');
var_dump($date);
$timezone  = new \DateTimeZone(str_replace(':', '', $UTC_offset));
$date->setTimezone($timezone);
var_dump($date);

结果:

class DateTime#205 (3) {
  public $date =>
  string(26) "2015-01-20 06:00:00.000000"
  public $timezone_type =>
  int(3)
  public $timezone =>
  string(3) "UTC"
}
class DateTime#205 (3) {
  public $date =>
  string(26) "2015-01-20 09:00:00.000000"
  public $timezone_type =>
  int(1)
  public $timezone =>
  string(6) "+03:00"
}

答案 3 :(得分:1)

您可能需要查看DateTime PHP扩展程序(默认情况下,它已启用并包含在所有PHP版本中&gt; = 5.2.0,除非它在编译时被特别禁用)。

它完成了你所需要的一切。

答案 4 :(得分:1)

无需将时区偏移量映射回时区标识符。许多时区共享相同的偏移量。

即使在一个国家/地区,这也存在问题。考虑到在美国,中央标准时间(America/Chicago)和东部夏令时(America/New_York)在一年中的不同时间使用-5偏移量。

同时考虑有时候这些时区同时使用-5。例如,2013年11月3日星期日上午1点,UTC-5可以是CDT或EST。你无法区分-5到哪个时区。

Details here.

答案 5 :(得分:0)

您也可以使用GMT时间,然后将其转换为您的要求

<?php
echo gmdate("M d Y H:i:s", mktime(0, 0, 0, 1, 1, 1998));
?>

格林威治标准时间指格林威治标准时间,这在全世界都很常见。

答案 6 :(得分:0)

现在DateTimeZone构造函数可以显式接受UTC偏移量,我知道你已经拥有它。

所以只是:

$timeZone = new DateTimeZone('+0100');

文档:

http://php.net/manual/en/datetimezone.construct.php

注意:根据该文档链接,这个新的构造函数用法自PHP 5.5.10起可用。

答案 7 :(得分:0)

这项工作对我来说:

function Get_Offset_Date($Offset, $Unixtime = false, $Date_Format = 'Y.m.d,H:i')
{
    try
    {
        $date   = new DateTime("now",new DateTimeZone($Offset));
        if($Unixtime)
        {
            $date->setTimestamp($Unixtime);
        }

        $Unixtime = $date->getTimestamp();
        return $date->format($Date_Format);
    }

    catch(Exception $e)
    {
        return false;
    }
}

要使用它,只需调用它来获取当前时间:

echo Get_Offset_Date('+2:00');

这是获取偏移日期(输入为unixtime)

echo Get_Offset_Date('+2:00',1524783867);