PHP UTC到当地时间

Joh*_*ohn 21 php utc dst

服务器环境

Redhat Enterprise Linux
PHP 5.3.5

问题

假设我有一个UTC日期和时间,例如2011-04-27 02:45,我想把它转换成我当地的时间,即America/New_York.

三个问题:

1.)我的代码可以解决问题,你同意吗?

<?php

date_default_timezone_set('America/New_York');  // Set timezone.

$utc_ts = strtotime("2011-04-27 02:45");  // UTC Unix timestamp.

// Timezone offset in seconds. The offset for timezones west of UTC is always negative,
// and for those east of UTC is always positive.
$offset = date("Z");

$local_ts = $utc_ts + $offset;  // Local Unix timestamp. Add because $offset is negative.

$local_time = date("Y-m-d g:i A", $local_ts);  // Local time as yyyy-mm-dd h:m am/pm.

echo $local_time;  // 2011-04-26 10:45 PM

?>
Run Code Online (Sandbox Code Playgroud)

2.)但是,$ offset的值是否会自动调整为夏令时(DST)?
3.)如果没有,我应该如何调整我的代码以自动调整DST?

谢谢 :-)

Tre*_*non 37

这将使用PHP本机DateTimeDateTimeZone类执行您想要的操作:

$utc_date = DateTime::createFromFormat(
                'Y-m-d G:i', 
                '2011-04-27 02:45', 
                new DateTimeZone('UTC')
);

$nyc_date = $utc_date;
$nyc_date->setTimeZone(new DateTimeZone('America/New_York'));

echo $nyc_date->format('Y-m-d g:i A'); // output: 2011-04-26 10:45 PM
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参见DateTime :: createFromFormat手册页.

在经历过和当前没有DST的时区之间进行一些实验后,我发现这将考虑DST.使用上述方法进行的相同转换会产生相同的结果时间.

  • 这也是为什么PHP为印第安纳州提供了7个不同的时区,以解释他们疯狂的不同DST规则:http://php.net/manual/en/timezones.php (2认同)

小智 5

我知道这是一个旧帖子,但是您需要添加另一行以获得正确的时间。

在转换为本地时间之前,您需要像这样将默认时区设置为 UTC(如果它是您提供的时间的时区):

function GmtTimeToLocalTime($time) {
    date_default_timezone_set('UTC');
    $new_date = new DateTime($time);
    $new_date->setTimeZone(new DateTimeZone('America/New_York'));
    return $new_date->format("Y-m-d h:i:s");
}
Run Code Online (Sandbox Code Playgroud)