我正在处理一个处理时间、日期和用户时区的PHP项目。
它需要准确,所以我将DateTime和一个时间戳作为UTC时间存储在DB中。
在UI/前端,我试图基于用户的DateTimes显示TimeZone。
我在下面做了一个简单的演示课程来演示我当前的问题。
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发布于 2013-09-21 19:33:49
DateTime说:
备注当$time参数是UNIX时间戳(例如@946684800)或指定时区(例如10-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),所以要适当地转移它。
发布于 2013-09-21 19:39:19
您调用了一个构造函数,这将在每次分配时区时调用,因此,基本上每个创建这个构造的新对象都首先被调用。
public function __construct()
{
$this->timeZone = new DateTimeZone('UTC');
$this->dateTime = new DateTime(null, $this->timeZone);
}当您使用UNIX时间戳时,它将始终返回UTC时区。
https://stackoverflow.com/questions/18936673
复制相似问题