dongxiong5546 2017-09-19 06:20
浏览 97
已采纳

在布尔值上调用成员函数format()

I want to find the difference between two dates and I have used date_diff for the same. When format function is applied on date_diff object it returns an error.

Call to a member function format() on boolean

$field_value is fetched from the database and it's format is dd/mm/YYYY. When I hard-code the values for $field_value and $indexing_value the following code works.

Everything is running fine till line number 8. I have tried outputting the value of

$diff->format("%R%a")

and it is returning exact value but the code gives error near the if statement.

$date = new DateTime();
$current_date = $date->format('d/m/Y');
$indexing_value = str_replace("/", "-", $field_value);
$current_value = str_replace("/", "-", $current_date);
$indexing_value = date_create($indexing_value);
$current_value = date_create($current_value);

$diff = date_diff($indexing_value, $current_value);
if ($diff->format("%R%a") < 0) {
    echo "1";
} else {
    echo "2";
}

Please let me know what is wrong with the above code.

  • 写回答

2条回答 默认 最新

  • drgovyk64676 2017-09-19 06:24
    关注

    add condition to check whether you got the diff or not, as it returns false if there is error . Check manual for the same

    $diff = date_diff($indexing_value, $current_value);
    if ($diff) {
        if ($diff->format("%R%a") < 0) {
            echo "1";
        }else{
            echo "2";
        }   
    }
    

    You are getting error because for some values the diff is not calculated and have value False in $diff

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?