dongwu8653 2018-12-31 18:41
浏览 104
已采纳

PHP - 如何修复date_format()错误'给定布尔值,而不是DateTimeInterface'?

I'm getting this error: "Warning: date_format() expects parameter 1 to be DateTimeInterface, boolean given in C:...\myFile.php on line 24"

I've tried that code using strtotime instead of time():

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

And works: //--> 2018/12/31

But can't understand why, because both strtotime, and time return same Unix timestamps.

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

I expected the same result wiht both codes. Any clue about what's happening?

  • 写回答

1条回答 默认 最新

  • dongqucheng3851 2018-12-31 19:09
    关注

    date_create() expects as first parameter a string representing date and time.

    Passing a number as you do (you pass time() that return the unix timestamp) will result in date_create returning false that of course cannot be parsed by date_format().

    You can read the documentation to see how the data string can be formatted.

    You can pass "now" if you want to create a DateTime object set to the present moment.

    $dtObj = date_create( "now", timezone_open("Europe/Oslo"));
    echo date_format($dtObj, "d-m-Y") . "<br>";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效