【发布时间】: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