6

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

Now it prints

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

I would like to have output like this

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

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.

I'm using PHP 7.0.8.

I meant something like this

<?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);

This code now output

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

I would like to have

{
    "date": "2016-10-27T11:23:52+00:00"
}
5
  • json_encode() does not manipulate any data you give it. If you put the date into the object/array you are encoding the way you want to see it it will stay that way. So fix the code that adds the date Commented Oct 27, 2016 at 10:59
  • Basically… manually format the date into a string before you json_encode it. Commented Oct 27, 2016 at 11:39
  • @deceze yes, it is probably the only way. I have to return date for articles, comments, threads... and more... So I thought it will be possible to convert it somehow automatically at one place. Commented Oct 27, 2016 at 11:54
  • what is the format for that type of date 2016-10-27 11:23:52.000000, I'm guessing yyyy-MM-dd HH:mm:ss ??? what's the last .000000 ? Commented Jan 19, 2017 at 15:52
  • 1
    Microseconds. They are added since some 5.x version of the PHP. This is Y-m-d H:i:s.u format according to us1.php.net/manual/en/function.date.php Commented Jan 23, 2017 at 13:00

1 Answer 1

26

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"}
Sign up to request clarification or add additional context in comments.

1 Comment

OMG, shame on me. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.