执行 json_encode 时 PHP 7.4 的日期时间问题我使用的是 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 个次要版本,您应该立即处理这个问题,这样可以为您省去很多麻烦,因为它是最新的,而不是解决不兼容问题以坚持使用不受支持的版本。

>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...