在给定 ISO 8601 日期时间和时区的情况下获取 PHP 的当地时间

Getting local time in PHP given a ISO 8601 datetime and timezone

我正在尝试根据祖鲁时间中的 ISO 8601 格式日期时间字符串和时区字符串获取本地时间。我阅读了有关 DateTime 对象和 DateTimeZone 的 PHP 文档,并且尝试了很多东西,但我似乎无法获得正确的本地时间。我现在拥有的:

$datetime = '2017-05-29T10:30:00Z'; // I'm getting this value from an API call
$timezone = 'Europe/Prague'; // I'm getting this value from an API call
$date = new \DateTime( $datetime, new \DateTimeZone( $timezone ) );
var_dump( $date->format('H:i') );
// I would expect it to be 12:30 since 29th May for this timezone would be GMT+2, but I get 10:30

所以很明显我遗漏了有关 DateTime 和 DateTimeZone 的一些信息 类,但我无法正确处理。谁能帮帮我?

试试这个代码:

date_default_timezone_set("Europe/Prague");
echo date('H:i');

它将以 24 小时格式打印日期和时间。

我认为混淆在于你所在的时区而不是日期时间字符串所在的时区。我在新奥尔良,所以我的时区是 'America/Chicago'。我会设置为:

date_default_timezone_set('America/Chicago');

然后,设置日期时间字符串来自的时区(我假设,Europe/Prague):

$datetimePrague = '2017-05-29T10:30:00Z';
$timezonePrague = 'Europe/Prague';

现在,当您创建 DateTime 对象时,将时间来源的日期时间和时区传递给它。

$datePrague = new \DateTime( $datetimePrague, new \DateTimeZone( $timezonePrague ) );

然后,获取DateTime对象的时间戳:

$timestamp = $datePrague->getTimestamp();

最后,将该时间戳连同您想要的格式一起传递给 date() 函数,您将获得与您所在的任何时区的 DateTime 等效的值:

date('H:i', $timestamp);

这是完整的代码,假设我住在新奥尔良,我想知道新奥尔良本地时间与 10:30 的布拉格时间是多少:

<?php

date_default_timezone_set('America/Chicago');

$datetimePrague = '2017-05-29T10:30:00Z';
$timezonePrague = 'Europe/Prague';
$datePrague = new \DateTime( $datetimePrague, new \DateTimeZone( $timezonePrague ) );
$timestamp = $datePrague->getTimestamp();
var_dump(date('H:i', $timestamp));

所以我终于做对了,对于任何感兴趣的人:

$datetime = '2017-05-29T10:30:00Z'; // I'm getting this value from an API call
$timezone = 'Europe/Prague'; // I'm getting this value from an API call
$date = new \DateTime( $datetime, new \DateTimeZone( 'UTC' ) ); // as the original datetime string is in Zulu time, I need to set the datetimezone as UTC when creating
$date->setTimezone( new \DateTimeZone( $timezone ) ); // this is what actually sets which timezone is printed in the next line
var_dump( $date->format('H:i') ); // yay! now it prints 12:30