Yii2: JSON::encode for DateTime

Created on 23 Dec 2019  路  9Comments  路  Source: yiisoft/yii2

What steps will reproduce the problem?

echo \yii\helpers\Json::encode(['date' => new \DateTime()]);

What is the expected result?

{"date":{"date":"2019-12-23 15:52:27.717576","timezone_type":3,"timezone":"UTC"}}

What do you get instead?

{"date":{}}

But when I run native php json_encode:
echo json_encode(['date' => new \DateTime()]);

Returns expected result:
{"date":{"date":"2019-12-23 15:52:27.717576","timezone_type":3,"timezone":"UTC"}}

Additional info

| Q | A
| ---------------- | ---
| Yii version | 2.0.31
| PHP version | 7.4.0 (cli)
| Operating system | Debian 10

php7 bug

Most helpful comment

All 9 comments

For yii3, consider whether it makes sense to support the current php output format ({"date":"2019-12-23 15:52:27.717576","timezone_type":3,"timezone":"UTC"}). I prefer unix timestamp (eliminate timezone), or RFC3339#5.6 format Y-m-d\TH:i:s.vP

Can't verify this issue. I did the following:
I added

        // @see https://github.com/yiisoft/yii2/issues/17760
        $data = ['date' => new \DateTime('now')];
        $this->assertSame('{"date":{}}', Json::encode($data));

to method testEncode() and got following resut:

Failed asserting that two strings are identical.
Expected :{"date":{}}
Actual   :{"date":{"date":"2019-12-24 09:38:26.801064","timezone_type":3,"timezone":"UTC"}}

I used yii 2.0.31 with php 7.2

Well, it works as expected on php 7.2 and 7.3 but I can stably reproduce issue on 7.4.0 and 7.4.1

For checking this issue I used Docker and php tags php:7.2-fpm, php:7.3-fpm, php:7.4-fpm, php:7.4.1-fpm

I can confirm this issue - it was changed in PHP 7.4. It seems that DateTime is somewhat hacky, since it should not contain public properties, and json_encode() is treated specially for BC reasons. It was already fixed for array cast: https://bugs.php.net/bug.php?id=78383

But foreach behavior is still inconsistent: https://3v4l.org/h99LLn

Could we cast to array in foreach BaseJson.php#L162?

Cast to array exposes also private and protected properties - it would be easier to add special condition for DateTime. But I would try to report it as PHP bug, since current behavior for DateTime is weird and inconsistent.

@rob006 would you please report a PHP bug?

Seems to unlikely being fixed on the PHP side.

Was this page helpful?
0 / 5 - 0 ratings