2017-09-19 49 views
1

我想查找兩個日期之間的差異,並且我使用date_diff表示相同的值。當格式化功能應用於date_diff對象時,它會返回錯誤。在布爾值上調用成員函數格式()

調用一個成員函數的格式()布爾

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

請讓我知道上面的代碼有什麼問題。

回答

1

添加條件來檢查您是否得到了差異,因爲如果出現錯誤,它將返回false。檢查manual爲同一

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

你得到錯誤,因爲對於一些價值不$diff

0

計算的diff和具有價值False請讓我知道什麼是錯的,上面的代碼。

有幾個問題與代碼:

  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"; 
} 
相關問題