Change output of DateTime in json_encode

后端 未结 1 431
無奈伤痛
無奈伤痛 2021-01-15 18:58

Is somehow possible to change output of json_encode([\'date\' => $dateTimeObj])?

Now it prints

{
    \"date\": {
        \"date\":          


        
相关标签:
1条回答
  • 2021-01-15 19:52

    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"}
    
    0 讨论(0)
提交回复
热议问题