为什么在尝试将 Carbon 转换为 DateTime 时出现错误?

Why do I get error when try to convert Carbon to DateTime?

我正在开发一个 Laravel 项目。我尝试使用 Carbon 创建 DateTime 对象。这是我试过的:

Carbon::createFromFormat('Y-m-d H:i:s', '2021-10-01T00:01:00')->toDateTime();

但是我的 phpstan 抱怨:Cannot call method toDateTime() on Carbon\Carbon|false.

为什么会出现这个错误?将 Carbon 转换为 DateTime 对象的正确方法是什么?

您的格式不正确,Carbon 无法创建时间。您缺少需要转义的 T。

Carbon::createFromFormat('Y-m-d\TH:i:s', '2021-10-01T00:01:00')->toDateTime();

Carbon 对象是已经 个 DateTime 对象。

class Carbon extends \DateTime

你可能想要 toDateTimeString,但如果你真的想要一个 DateTime 对象,你已经有了一个,只是在上面撒了一点 Carbon 语法糖。

如果您确实需要 DateTime 对象,->toDate() 函数就是您要找的。

https://carbon.nesbot.com/docs/

Return native DateTime PHP object matching the current instance.

如果 PHPStan 报错,那是因为静态分析(不执行代码)无法正确确定类型。由于 Carbon 扩展了 DateTimePHP documentation 可以帮助调用此方法:

Returns a new DateTime instance or false on failure.

因此,为了确保代码在静态分析方面是可靠的,您需要将其拆分:

$object = Carbon::createFromFormat('Y-m-d H:i:s', '2021-10-01T00:01:00');

if (!$object instanceof Carbon) {
  throw new RuntimeException('could not parse date');
}

$object->toDateTime();

区别:现在,当调用 toDateTime() 时,PHPStan 可以安全地假设 $objectCarbon 类型


正如其他人指出的那样:运行 该代码也会产生错误,因为您尝试解析的日期格式与输入日期不匹配。但这超出了 PHPStan 的范围,PHPStan 执行代码