You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP从含9位微秒的ISO字符串创建Carbon/DateTime对象?

解决PHP/Carbon解析带9位小数秒的ISO8601字符串问题

一、原生PHP创建DateTime对象

方法1:直接实例化(推荐)

PHP的DateTime类原生支持解析这种带纳秒级小数秒的ISO8601格式(末尾的Z代表UTC时区),无需手动指定格式:

$dateStr = '2022-06-21T05:52:46.648533678Z';
$datetime = new DateTime($dateStr);
print_r($datetime);

方法2:使用createFromFormat

若必须手动指定格式,注意时区部分要用\Z匹配末尾的Z(P仅匹配±HH:mm格式的偏移)。u格式符对应6位微秒,字符串的9位小数会被自动截断到6位,不影响对象创建:

$datetime = DateTime::createFromFormat('Y-m-d\TH:i:s.u\Z', '2022-06-21T05:52:46.648533678Z');

二、Carbon创建对象

方法1:使用parse方法(最简单)

Carbon继承自DateTime,parse方法可直接识别该格式:

use Carbon\Carbon;

$carbon = Carbon::parse('2022-06-21T05:52:46.648533678Z');
echo $carbon->toIso8601String();

方法2:使用createFromFormat

和原生DateTime逻辑一致,修正格式符中的时区部分为\Z即可:

use Carbon\Carbon;

$carbon = Carbon::createFromFormat('Y-m-d\TH:i:s.u\Z', '2022-06-21T05:52:46.648533678Z');

报错原因说明

你之前使用P作为时区格式符,但P仅匹配±HH:mm形式的时区偏移,而字符串末尾是代表UTC的Z,格式不匹配导致时区解析失败,从而抛出The timezone could not be found in the database错误。

内容的提问来源于stack exchange,提问作者pixelpenguin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 18:57:09