如何在PHP中将json datetime转换为datetime

如何在PHP中将json datetime转换为datetime,php,datetime,Php,Datetime,我在数据库中存储了一个json格式的datetime,需要时我需要用datetime重新转换它 一旦解码,它就是一个关联的数组: [date] => 2021-05-20 17:00:00.000000 [timezone_type] => 3 [timezone] => UTC 我有点搞不懂如何把这个变成一个时区正确的日期时间 我发现 时区可以是DateTime对象中的三种不同类型之一: 1. Type 1: A UTC offset, such as in new Dat

我在数据库中存储了一个json格式的datetime,需要时我需要用datetime重新转换它

一旦解码,它就是一个关联的数组:

[date] => 2021-05-20 17:00:00.000000
[timezone_type] => 3
[timezone] => UTC
我有点搞不懂如何把这个变成一个时区正确的日期时间

我发现

时区可以是DateTime对象中的三种不同类型之一:

1. Type 1: A UTC offset, such as in new DateTime("17 July 2013 -0300");
2. Type 2; A timezone abbreviation, such as in new DateTime("17 July 2013 GMT");
3. Type 3: A timezone identifier, such as in new DateTime( "17 July 2013", new DateTimeZone("Europe/London"));
但我不确定如何将其应用于我目前的数据。我有3个参数,所有这些解决方案只使用2个参数

以下是我希望使用的代码:

/**
 * @return array|null
 * @throws JsonException
 * @throws Exception
 */
public function getContext(): ?array
{
    $context = json_decode($this->context, true, 512, JSON_THROW_ON_ERROR);
    foreach ($context as $key => $value){
        if(is_array($value) && isset($value['date'], $value['timezone_type'], $value['timezone'])){
            $date = new DateTime($value['date'] . '-' . $value['timezone_type'] );
            $context[$key] = $date;
            $context[$key] = $date;
        }
    }
    return array_unique($context);

它应该显示
18h00
,但如果没有时区,则显示
17h00
,如果是时区,则显示
20h00

,您所拥有的是使用
DateTimeInterface
对象输入
json\u encode()
的结果。时区类型是不感兴趣的内部字段:

$dt = new DateTime('2021-05-19 20:30:00 +0200');
echo json_encode($dt), PHP_EOL;
$dt = new DateTime('2021-05-19 20:30:00 CEST');
echo json_encode($dt), PHP_EOL;
$dt = new DateTime('2021-05-19 20:30:00 Europe/Berlin');
echo json_encode($dt), PHP_EOL;

您可以忽略这一点,只需使用我的示例中的另外两个值构建一个字符串。

时区类型似乎不相关。你能展示一下你的代码并解释一下你在将其转换成日期对象时遇到了什么问题吗?我编辑了这个问题,添加了你要求的新日期时间($value['date'].-。$value['timezone\u type'])会将时区类型解释为实际的UTC偏移量。我觉得很难相信。JSON不转换时区。如果该值具有
17:00
UTC
,则该对象被编码为JSON。如果DateTime对象的时区在JSON编码之前发生了更改,这是完全不同的。因此,无论如何,在重新创建对象时,只需使用
timezone
而不是
timezone\u type
,就可以了。
{"date":"2021-05-19 20:30:00.000000","timezone_type":1,"timezone":"+02:00"}
{"date":"2021-05-19 20:30:00.000000","timezone_type":2,"timezone":"CEST"}
{"date":"2021-05-19 20:30:00.000000","timezone_type":3,"timezone":"Europe\/Berlin"}