【问题标题】:Difficulty converting time between timezones时区之间的时间转换困难
【发布时间】:2014-06-06 16:04:14
【问题描述】:

我正在尝试将午夜 GMT 转换为不同的时区。我们有一个从午夜到午夜的每日测验,我希望能够向人们动态显示不同的时区,以便它随着 DST 自动变化。

按照this answer我想出了这段代码

$dateFormat = 'h:i a';
$date = new DateTime(gmdate('Y-m-d'), new DateTimeZone('GMT'));
$date->setTimezone(new DateTimeZone('Europe/London'));
$tzWesternEurope = date($dateFormat);
$date->setTimezone(new DateTimeZone('Europe/Berlin'));
$tzCentralEurope = date($dateFormat);
$date->setTimezone(new DateTimeZone('Europe/Athens'));
$tzEasternEurope = date($dateFormat);
// ... And so for 17 different time zones around the world.

但是它不起作用。正如您从这个eval.in 示例中看到的那样,所有时区都显示相同,并显示错误的时间。我做错了什么?

我尝试将gmdate('Y-m-d') 更改为时间、00:00 和12am,但均未成功。我尝试使用 UTC 而不是 GMT 作为基础 DateTimeZone,但同样没有区别。

【问题讨论】:

    标签: php datetime timezone


    【解决方案1】:

    您从未真正使用过$date。您不断更改时区,但随后忽略它并直接转到完全不相关的 date() 函数。

    您需要使用DateTime::format() 以您想要的格式和时区输出日期。

    $dateFormat = 'h:i a';
    $date = new DateTime(null, new DateTimeZone('GMT'));
    $date->setTimezone(new DateTimeZone('Europe/London'));
    $tzWesternEurope = $date->format($dateFormat);
    $date->setTimezone(new DateTimeZone('Europe/Berlin'));
    $tzCentralEurope = $date->format($dateFormat);
    

    【讨论】:

    • 嘎!谢谢你。我怎么会这么白痴。我已经盯着这个看了好几个小时了,没有看到。谢谢。
    猜你喜欢
    • 2016-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多