【问题标题】:Change output of DateTime in json_encode更改 json_encode 中 DateTime 的输出
【发布时间】:2016-10-27 10:57:23
【问题描述】:

是否有可能更改json_encode(['date' => $dateTimeObj]) 的输出?

现在打印出来了

{
    "date": {
        "date": "2016-10-27 11:23:52.000000",
        "timezone_type": 3,
        "timezone": "Europe/Paris"    
    }
}

我想要这样的输出

{
    "date": "2016-10-27T11:23:52+00:00"
}

我的第一个想法是创建自己的 DateTime 类,它将扩展 DateTime 并覆盖 jsonSerialize,但 DateTime 没有实现 JsonSerializable 接口,__toString 也没有帮助。

我使用的是 PHP 7.0.8。

我的意思是这样的

<?php    
MyDateTime extends \DateTime implements jsonSerialize 
{
    public function jsonSerialize() // this is never called
    {
       return $this->format("c");
    }
}

$datetime = new MyDatetime();

$output = [
    'date' => $datetime;  // want to avoid $datetime->format("c") or something like this everywhere
];

json_encode($output);

此代码现在输出

{
    "date": {
        "date": "2016-10-27 11:23:52.000000",
        "timezone_type": 3,
        "timezone": "Europe/Paris"    
    }
}

我想要

{
    "date": "2016-10-27T11:23:52+00:00"
}

【问题讨论】:

  • json_encode() 不会操纵您提供的任何数据。如果您将日期放入对象/数组中,您将按照您希望看到的方式进行编码,它将保持这种方式。所以修复添加日期的代码
  • 基本上……在json_encode它之前手动将日期格式化为字符串。
  • @deceze 是的,这可能是唯一的方法。我必须返回文章、cmets、线程......等等的日期......所以我认为可以在一个地方以某种方式自动转换它。
  • 那种日期2016-10-27 11:23:52.000000的格式是什么,我猜yyyy-MM-dd HH:mm:ss ???最后一个.000000是什么?
  • 微秒。它们是从 PHP 的某些 5.x 版本开始添加的。这是Y-m-d H:i:s.u 格式,根据us1.php.net/manual/en/function.date.php

标签: php json datetime


【解决方案1】:

在更改了一些细节之后,尤其是接口名称,您的代码在 PHP 7.0.14 上对我来说运行良好。

<?php

class MyDateTime extends \DateTime implements \JsonSerializable
{
    public function jsonSerialize()
    {
       return $this->format("c");
    }
}

$datetime = new MyDatetime();

$output = [
    'date' => $datetime,
];

echo json_encode($output);
// Outputs: {"date":"2017-02-12T17:34:36+00:00"}

【讨论】:

  • 天啊,真丢人。谢谢!
猜你喜欢
  • 2013-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-28
  • 1970-01-01
  • 2014-05-04
相关资源
最近更新 更多