PHP - 如何修复 date_format() 错误 'boolean given, instead of DateTimeInterface'?

PHP - How to fix date_format() error 'boolean given, instead of DateTimeInterface'?

我收到此错误: "Warning: date_format() expects parameter 1 to be DateTimeInterface, boolean given in C:...\myFile.php on line 24"

我试过使用 strtotime 而不是 time() 的代码:

$strDate = time();
$str = strtotime($strDate);
$date = date_create($str);
echo date_format($date, "Y/m/d");

并且有效://--> 2018/12/31

但不明白为什么,因为 strtotime 和 time return 相同的 Unix 时间戳。

$dtObj = date_create(time(), timezone_open("Europe/Oslo"));
echo $dtObj . '</br>'; // Works ok
date_format($dtObj, "d-m-Y"); // This throws error

我预计两种代码的结果相同。关于发生了什么的任何线索?

date_create() 期望作为第一个参数的 string 表示日期和时间。

像你一样传递一个数字(你传递 time() 那 return unix 时间戳 )将导致 date_create returning false 当然不能被 date_format().

解析

您可以阅读 documentation 以了解如何格式化数据字符串。

如果要创建一个设置为当前时刻的 DateTime 对象,可以传递 "now"

$dtObj = date_create( "now", timezone_open("Europe/Oslo"));
echo date_format($dtObj, "d-m-Y") . "<br>";