在布尔值上调用成员函数format() [英] Call to a member function format() on boolean

查看:88
本文介绍了在布尔值上调用成员函数format()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到两个日期之间的差异,并且我使用了 date_diff 来表示相同的日期。在 date_diff 对象上应用格式函数时,它将返回错误。

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.


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

$ field_value 是从数据库中获取的,其格式为 dd / mm / YYYY 。当我对 $ field_value $ indexing_value 以下代码有效。

$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.

一切正常,直到第8行为止。我尝试输出

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

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

并且返回精确值,但是代码在if语句附近给出错误。

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.

推荐答案

添加条件以检查您是否获得了差异,因为如果有error,它将返回false。检查手册是否相同

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";
    }   
}

由于某些值的差异是未计算并在 $ diff

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

这篇关于在布尔值上调用成员函数format()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆