PHP中的TimeZones问题

时间:2013-09-21 19:24:50

标签: php datetime timezone

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

它需要准确,所以我将数据库中的DateTime和Timestamp存储为UTC时间。

在UI /前端我试图根据用户的TimeZone显示DateTimes。

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

createTimeCard()方法应该在UTC时创建一个DateTime,这似乎工作正常。

get12HourDateTime($date, $format = 'Y-m-d h:i:s a')方法用于在自己的时区中以及12小时格式时间内向用户显示DateTime。不幸的是,这是我的问题开始的地方无论在这里设置什么时区,它总是返回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

2 个答案:

答案 0 :(得分:2)

DateTime说:

  

注意   当$ 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时区初始化DateTime(因为它对应于$date),因此请适当地移动它。

答案 1 :(得分:0)

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

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

当您使用UNIX TIMESTAMP时,它将始终在UTC时区返回。