php - 使用 PHP DateTime 解析和转换时区 PST 到 PDT(GMT -8 到 GMT -7)

标签 php datetime timezone

我在使用 PHP DateTime 将 GMT -8 时区 (PST) 接收的日期转换为 GMT -7 (PDT) 时区的人类可读格式时遇到困难。

这是一个例子:

$tz = new DateTimeZone('America/Los_Angeles');  
$saleEndDate = new DateTime("2016-11-07T17:30:00-08:00");
$saleEndDate->setTimezone($tz);
echo $saleEndDate->format('Y-m-d H:i:s');

以上代码的输出为:2016-11-07 17:30:00。但是,它应该显示 2016-11-07 18:30:00,因为 America/Los_Angeles 现在处于夏令时(GMT -7,PDT)。

根据我在 DateTime docs 中阅读的内容,new DateTime 命令应该能够解释字符串 2016-11-07T17:30:00-08:00 具有 GMT -8 时区:

The timezone parameter and the current timezone are ignored when the time parameter either contains a UNIX timestamp (e.g. 946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).

即便如此,我认为 DateTime 无法正确识别 GMT -8。

有谁知道在时区之间正确转换需要什么方法?

更新:

我还尝试将 DateTimeZone 作为第二个参数传递给 DateTime 构造函数,但也无济于事:

$tz = new DateTimeZone('America/Los_Angeles');  
$saleEndDate = new DateTime("2016-11-07T17:30:00-08:00", new DateTimeZone("America/Los_Angeles"));
$saleEndDate->setTimezone($tz);
echo $saleEndDate->format('Y-m-d H:i:s');

也不起作用:

$tz = new DateTimeZone('America/Los_Angeles');  
$saleEndDate = new DateTime("2016-11-07T17:30:00", new DateTimeZone("PST"));
$saleEndDate->setTimezone($tz);
echo $saleEndDate->format('Y-m-d H:i:s');

也不起作用:

$tz = new DateTimeZone("PDT");  
$saleEndDate = new DateTime("2016-11-07T17:30:00", new DateTimeZone("PST"));
$saleEndDate->setTimezone($tz);
echo $saleEndDate->format('Y-m-d H:i:s');

最佳答案

不是最好的,但这是我能想到的唯一方法

$tz = new DateTimeZone('America/Los_Angeles');  
$saleEndDate = new DateTime("2016-11-07T17:30:00-08:00");
$saleEndDate->setTimezone($tz);
$stamp = $saleEndDate->format('U');
$zone = $tz->getTransitions($stamp, $stamp);
if(!$zone[0]['isdst']) $saleEndDate->modify('+1 hour');
echo $saleEndDate->format('Y-m-d H:i:s');

我在这里做的是使用 DateTimeZone::getTransitions function以确定您提供的日期是否为夏令时。如果不是,我们加一小时。请注意,这不会更改时区,它只是更正 DST 偏移

You can see it in action here

关于php - 使用 PHP DateTime 解析和转换时区 PST 到 PDT(GMT -8 到 GMT -7),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39736509/

相关文章:

php - 在议程中查找第一个空闲日期

c# - 如何在 C# 中使用日期格式作为常量?

r - POSIXct 和 xts 中的时区,从 R 中的 GMT 转换

Postgresql 没有正确转换时区

python - 如何在python中获取时区感知午夜日期时间?

php - 使用android检查mysql数据

PHP 和 MySQLi close()

php - 使用 Yii::app()->user 时出现问题

java - 如何解释这些时间戳?

python - 在 Python 中使用日期时间的每月总金额