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>";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?