【问题标题】:Changing timezone of a retrieved date in php在php中更改检索日期的时区
【发布时间】:2013-09-15 08:18:35
【问题描述】:

我正在从数据库中检索格式为 2013-09-15 08:45:00 的日期,该日期设置为 UTC,我需要将其更改为另一个动态时区(基于用户)

目前为止

$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 小时。

【问题讨论】:

  • 这里有一个可能有帮助的答案:stackoverflow.com/questions/8114195/…
  • 谢谢,但我已经尝试过了 :( 它的行为似乎与我上面的代码相同。
  • hmm..您已将其标记为 drupal。你试过drupal format_date 功能吗?
  • 不,我没有。会的,谢谢。
  • 似乎没有什么不同。

标签: php date datetime drupal


【解决方案1】:

您输入的日期时间是 UTC,而不是用户的时区。因此,首先您必须在 UTC 中创建日期时间对象,然后将时区设置/更改为用户的:

$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() 即可:

$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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-09
    • 2014-06-15
    • 1970-01-01
    • 2017-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多