【问题标题】:Call to a member function format() on boolean在布尔值上调用成员函数 format()
【发布时间】:2017-09-19 14:56:54
【问题描述】:

我想找出两个日期之间的差异,我也使用了date_diff。在date_diff 对象上应用格式函数时,它会返回错误。

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

$field_value 从数据库中获取,格式为dd/mm/YYYY。当我对 $field_value$indexing_value 的值进行硬编码时,以下代码有效。

在第 8 行之前一切都运行良好。我尝试输出

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

它返回的是准确的值,但是代码在 if 语句附近给出了错误。

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

请告诉我上面的代码有什么问题。

【问题讨论】:

    标签: php date


    【解决方案1】:

    添加条件来检查你是否得到了差异,因为如果有错误它返回 false 。检查manual是否相同

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

    您收到错误,因为对于某些值,未计算差异并且在 $diff 中具有值 False

    【讨论】:

      【解决方案2】:

      请告诉我上面的代码有什么问题。

      代码有几个问题:

      1. 你不检查date_create()返回的值;它返回FALSE on error

      2. 格式化$date 然后从结果字符串创建$current_value 有什么意义?如果您不关心时间组件并且只需要使用DateTime 对象的日期部分,您可以使用其setTime() 方法将时间组件设置为0

      3. 当您知道日期的格式时,使用str_replace() 来操作日期的文本表示有什么意义? DateTime::createFromFormat() 可用于将字符串解析为DateTime 对象。

      4. 无需计算两个日期的差及其格式并将值与0 进行比较。 DateTime 对象可以直接比较。

      总而言之,你需要的所有代码是:

      // Current date & time
      $today = new DateTime();
      // Ignore the time (change $today to "today at midnight")
      $today->setTime(0, 0, 0);
      
      // Parse the value retrieved from the database
      $field = DateTime::createFromFormat('d/m/Y', $field_value);
      // We don't care about the time components of $field either (because the time
      // is not provided in the input string it is created using the current time)
      $field->setTime(0, 0, 0);
      
      // Directly compare the DateTime objects to see which date is before the other
      if ($field < $today) {
          echo "1";
      } else {
          echo "2";
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-25
        • 2021-05-23
        • 2018-12-17
        • 2018-10-20
        相关资源
        最近更新 更多