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

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 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理