执行 json_encode 时 PHP 7.4 的日期时间问题(我正在使用 Carbon)

Datetime issue with PHP 7.4 when doing json_encode (I am using Carbon)

我已将 PHP 从 7.0 升级到 7.4,当我将数据时间放入 json_encode 时,我的代码表现不一样。 我在 PHP 个错误中看到了这个问题,但我不知道如何修复它。 Bugs.php bug 78383

现在,如果我对日期时间执行 json_decode,我会得到日期的空数组 []。

对于此代码:

$dataTest['text'] = "some text for the example";
$dataTest['date'] = Carbon::now();
$dateEncode = json_encode($dataTest);
$dateDecode = json_decode($dateEncode, TRUE);
dd($dataTest, $dateEncode, $dateDecode);

我得到:

array:2 [▼
  "text" => "some text for the example"
  "date" => Carbon {#905 ▼
    +"date": "2021-04-14 10:03:28.736535"
    +"timezone_type": 3
    +"timezone": "Europe/Madrid"
  }
]
"{"text":"some text for the example","date":[]}"
array:2 [▼
  "text" => "some text for the example"
  "date" => []
]

我可以强制 Carbon 成为 json_encode 之前的数组,但是要修复我的所有代码需要做很多工作 对于此代码:

$dataTest['text'] = "some text for the example";
$dataTest['date'] = (array)Carbon::now();
$dateEncodeArray = json_encode($dataTest);
$dateDecodeArray = json_decode($dateEncodeArray, TRUE);
dd($dateEncodeArray, $dateDecodeArray );

我得到:

"{"text":"some text for the example","date":{"date":"2021-04-14 10:09:32.481792","timezone_type":3,"timezone":"Europe\/Madrid"}}"
array:2 [▼
  "text" => "some text for the example"
  "date" => array:3 [▼
    "date" => "2021-04-14 10:09:32.481792"
    "timezone_type" => 3
    "timezone" => "Europe/Madrid"
  ]
]

我正在使用 Carbon 1(nesbot/carbon 1.32.0 DateTime 的简单 API 扩展。)

有人遇到同样的问题吗? 非常感谢,

只要将 Carbon 更新到更新的版本就可以了:

$ composer require nesbot/carbon "^2.46"

现在你可以安全地做:

$data = json_decode(json_encode(['date' => Carbon::now()]), true);

被甩了,那会给你:

array (

  'date' => '2021-04-14T12:53:04.403585Z',
)

如果你需要暂时留在 Carbon 1.x,你也可以尝试屏蔽 Carbon:

use Carbon\Carbon as Charcoal; // Alias Carbon

class Carbon { // Mask original Carbon

    public static function __callStatic($method, $args) {

        // Whatever the given Carbon method returns, cast it to an array
        return (array) Charcoal::{$method}(...$args);  
    }

    // Add more methods as needed 
}

您可以为 Carbon 1 和 2 自定义 Carbon 实例在 JSON 中以您想要的任何格式输出的方式:

Carbon::serializeUsing(function ($date) {
    return $date->tz('UTC')->format('Y-m-d\TH:i:s.up');
});

echo json_encode(Carbon::now());

以上将为您提供 Carbon 2 默认提供的相同格式。

显然,你应该升级,你落后了 54 个次要版本,你应该立即处理这个问题,它会为你节省很多进一步的麻烦,而不是解决不兼容问题以坚持不受支持的版本。