DateTime对象错误:在布尔值上调用成员函数format()

时间:2017-07-25 19:43:10

标签: php datetime datetime-format

  

致命错误:未捕获错误:调用成员函数格式()   布尔在/homepages/21/*****/*****/******/card/upload.php:29堆栈   跟踪:#0 {main}被抛入   第29行/homepages/21/******/*****/*****/card/upload.php

$newarray['date'] = DateTime::createFromFormat("j M Y", $arry[0])->format("Y-m-d");

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

很明显,您通过$arry[0]传递了无效的日期表达。

这是demo

// it works when $arry[0] is valid
$arry=['28 Jan 2017'];
$newarray['date'] = DateTime::createFromFormat("j M Y", $arry[0])->format("Y-m-d");
echo $newarray['date'];

echo "\n\n";

// it doesn't otherwise
$arry=['28 Mon 2017'];  // or an empty string, etc.
$newarray['date'] = DateTime::createFromFormat("j M Y", $arry[0])->format("Y-m-d");
echo $newarray['date'];

输出:

2017-01-28

<br />
<b>Fatal error</b>:  Uncaught Error: Call to a member function format() on boolean in [...][...]:16
Stack trace:
#0 {main}
  thrown in <b>[...][...]</b> on line <b>16</b><br />