Changing timezone of a retrieved date in php

只谈情不闲聊 提交于 2020-01-02 06:15:11

问题


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)

So far I've got

$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');

But it doesn't change the timezone. Any ideas what's wrong? It should be +2 hours in my case.


回答1:


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
)
*/

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
)
*/

p.s. because input 2013-09-15 08:45:00 is in standard datetime format, you don't need to use DateTime::createFromFormat.



来源:https://stackoverflow.com/questions/18810359/changing-timezone-of-a-retrieved-date-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!