在json_encode中更改DateTime的输出 [英] Change output of DateTime in json_encode

查看:145
本文介绍了在json_encode中更改DateTime的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is somehow possible to change output of 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也没有帮助.

My first idea was to create my own DateTime class which will extends DateTime and override jsonSerialize, but DateTime does not implement JsonSerializable interface and __toString did not help too.

我正在使用PHP 7.0.8.

I'm using 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"
}

推荐答案

在更改了一些细节(特别是接口名称)之后,您的代码在PHP 7.0.14上对我来说正常工作.

After changing a few details, notably the interface name, your code works just fine for me on 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"}

这篇关于在json_encode中更改DateTime的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆