PHP 中的时区问题


Trouble with TimeZones in PHP

我正在做一个处理时间和日期以及用户时区的PHP项目。

它需要准确,所以我将日期时间和时间戳存储在数据库中作为 UTC 时间。

在UI/前端,我尝试根据用户的时区显示日期时间。

我在下面制作了这个快速的小演示课程来演示我当前的问题。

createTimeCard()方法应该在UTC时间内创建一个日期时间,这似乎工作得很好。

get12HourDateTime($date, $format = 'Y-m-d h:i:s a') 方法用于向拥有自己的时区的用户显示日期时间,也以 12 小时格式的时间显示日期时间。 不幸的是,这就是我的问题开始的地方。 无论此处设置什么时区,它始终返回 UTC 时间!

谁能帮我弄清楚我做错了什么?

<?php
class TimeTest{
    public $dateTime;
    public $dateFormat = 'Y-m-d H:i:s';
    public $timeZone;
    public function __construct()
    {
        $this->timeZone = new DateTimeZone('UTC');
        $this->dateTime = new DateTime(null, $this->timeZone);
    }
    // Create a new time card record when a User Clocks In
    public function createTimeCard()
    {
        $dateTime = $this->dateTime;
        $dateFormat = $this->dateFormat;
        // Create both Timecard and timecard record tables in a Transaction
        $record = array(
            'clock_in_datetime' => $dateTime->format($dateFormat),
            'clock_in_timestamp' => $dateTime->getTimestamp()
        );
        return $record;
    }


    // Get 12 hour time format for a DateTime string
    // Simulates getting a DateTime with a USER's TimeZone'
    public function get12HourDateTime($date, $format = 'Y-m-d h:i:s a')
    {
        $timeZone = new DateTimeZone('America/Chicago');
        $date = new DateTime($date, $timeZone);
        // Also tried this with no luck
        $date->setTimezone(new DateTimeZone('America/Chicago'));
        return $date->format($format) ;
    }

}

$timeCard = new TimeTest;
$records = $timeCard->createTimeCard();
echo '<pre>';
print_r($records);
echo '</pre>';
echo $timeCard->get12HourDateTime($records['clock_in_datetime'], 'Y-m-d h:i:s a');
?>

输出

Array
(
    [clock_in_datetime] => 2013-09-21 19:28:01
    [clock_in_timestamp] => 1379791681
)
//This is in 12 hour format but is not in the new time zone!
2013-09-21 07:28:01 pm

日期时间 说:

注意 当$time参数是 UNIX 时间戳(例如 @946684800)或指定时区(例如 2010-01-28T15:00:00+02:00)时,将忽略 $timezone 参数和当前时区。

是这样吗?

也许尝试一下, setTimezone()

public function get12HourDateTime($date, $format = 'Y-m-d h:i:s a')
{
    $date = new DateTime($date);
    $date->setTimezone(new DateTimeZone('America/Chicago'));
    return $date->format($format) ;
}

编辑

public function get12HourDateTime($date, $format = 'Y-m-d h:i:s a')
{
    $date = new DateTime($date, new DateTimeZone('UTC'));
    $date->setTimezone(new DateTimeZone('America/Chicago'));
    return $date->format($format) ;
}

由于您首先要使用 UTC 时区初始化日期时间(因为这对应于 $date ),因此请适当地移动它。

你调用了一个构造函数,每次都会分配时区,所以基本上每个创建这个构造的新对象都被调用。

public function __construct()
{
    $this->timeZone = new DateTimeZone('UTC');
     $this->dateTime = new DateTime(null, $this->timeZone);
}

当您使用UNIX时间戳时,它将始终以UTC时区返回。