在php中更改检索日期的时区
我正在从数据库中检索格式为 2013-09-15 08:45:00 的日期,该日期设置为 UTC,我需要将其更改为另一个动态时区(基于用户)
I am retrieving a date in format of 2013-09-15 08:45:00 from the database, which is set in UTC and I need to change it to another dynamic timezone (based on user)
到目前为止我有
$datetime = $row->field_data_field_performance_times_field_performance_times_v;
$eventDate = DateTime::createFromFormat('Y-m-d H:i:s', $datetime, new DateTimeZone($user->timezone));
$performance_time = date_format($eventDate, 'l, j F, Y, H:i');
但它不会改变时区.任何想法有什么问题?就我而言,应该是 +2 小时.
But it doesn't change the timezone. Any ideas what's wrong? It should be +2 hours in my case.
推荐答案
您输入的日期时间是 UTC,而不是用户的时区.因此,首先您必须在 UTC 中创建日期时间对象,然后将时区设置/更改为用户的 :
Your input datetime is in UTC, not user's timezone. So first you must create datetime object in UTC, and then set/change timezone to user's :
$dt = new DateTime('2013-09-15 08:45:00', new DateTimeZone('UTC'));
print_r($dt);
/*
DateTime Object
(
[date] => 2013-09-15 08:45:00
[timezone_type] => 3
[timezone] => UTC
)
*/
现在您有 UTC 时区的日期时间.如果您想更改时区,只需在 DateTime 对象上调用 ->setTimezone()
:
Now you have datetime in UTC timezone. If you wish to change timezone, just call ->setTimezone()
on DateTime object :
$dt->setTimezone(new DateTimeZone('Europe/Berlin'));
print_r($dt);
/*
DateTime Object
(
[date] => 2013-09-15 10:45:00
[timezone_type] => 3
[timezone] => Europe/Berlin
)
*/
附言因为输入 2013-09-15 08:45:00
是标准的日期时间格式,所以你不需要使用 DateTime::createFromFormat
.
p.s. because input 2013-09-15 08:45:00
is in standard datetime format, you don't need to use DateTime::createFromFormat
.
相关文章