2017-07-15 182 views
2

我已經在StackOverflow上看到了幾個不同的DateTime比較,但我似乎無法弄清楚。我需要能夠從數據庫中檢索一行,將DateTime與當前DateTime進行比較,然後評估是否它。PHP - 將數據庫日期時間與當前日期時間進行比較

在這種情況下,我需要檢查當前行是否已過期。

if (strtotime(new DateTime()) > strtotime($row['expiration_date'])) { 
    $response = 'Valid Coupon!'; 
} else { 
    $response = 'Coupon Expired'; 
} 

我試過了幾種不同的方法,但沒有一種看起來沒有問題。

"2017-07-15 13:42:31 > 2017-07-15 14:27:31" 
// and 
"2017-07-15 13:42:31 > 2017-07-14 13:03:04" 

兩者都作爲有效的優惠券返回。

我已經嘗試了一些東西,但似乎無法弄清楚爲什麼這些日期不能正常工作。有什麼想法嗎?

回答

3

使用->format

if (strtotime((new DateTime())->format("Y-m-d H:i:s")) > strtotime($row['expiration_date'])) { 
    $response = 'Valid Coupon!'; 
} else { 
    $response = 'Coupon Expired'; 
} 

檢查這個活:https://eval.in/833030

或者你可以使用

(new DateTime())->getTimestamp(); 

而不是

strtotime((new DateTime())->format("Y-m-d H:i:s")); 

選中此項:https://eval.in/833038

2

您應該將您的new DateTime()和離港日期和時間更改爲Unix時間戳。 將日期轉換爲Unix時間戳時,它將以數字格式顯示。這樣,你會比較你的價值。

例如:

$current_date = strtotime(new DateTime); //your current date and time 
$expatriation_date = strtotime($row['expiration_date']); //your database data and time values // 
if($current_date > expatriation_date){ 
    $response = 'Valid Coupon!';    
} 
else{ 
    $response = 'Coupon Expired'; 
} 

你的當前日期和時間在Unix時間戳是「1500118951」和外派日期和時間在Unix時間戳是「1500121651」。您可以輕鬆比較您的價值。

+0

這是很好的建議。這有什麼缺點嗎? – Jacob

+1

不,我認爲不是。因爲這是找到解決方案的簡單方法。我以前使用過這種技術。 –

相關問題