2013-02-26 7 views
15

私は日付が未来であるか否かを判断しようとしていますを使用して、将来的にある場合DateTimeオブジェクトを使用して、決定しますが、それは常に正戻ってくる:問題PHPは - 日付がDateTimeオブジェクト

$opening_date = new DateTime($current_store['openingdate']); 
$current_date = new DateTime(); 
$diff = $opening_date->diff($current_date); 
echo $diff->format('%R'); // + 

if($diff->format('%R') == '+' && $current_store['openingdate'] != '0000-00-00' && $current_store['openingdate'] !== NULL) { 
    echo '<img id="openingsoon" src="/img/misc/openingsoon.jpg" alt="OPENING SOON" />'; 
} 

それは常に正であるので、画像が表示されないようにする必要があります。

私は何か愚かなことをする必要がありますが、それは何ですか、それは私を不気味に運転しています!

答えて

49

これはあなたの考えるよりも簡単です。あなたは通常の比較演算子でDateTimeオブジェクトを比較することができ

$opening_date = new DateTime($current_store['openingdate']); 
$current_date = new DateTime(); 

if ($opening_date > $current_date) 
{ 
    // not open yet! 
} 
9

これにはDateTimeオブジェクトは必要ありません。試してみてください:

$now = time(); 
if(strtotime($current_store['openingdate']) > $now) { 
    // then it is in the future 
} 
+5

あなたは日時を使用します他の理由のためにではなく、*より良い*ためオブジェクト。 'strtotime()'の範囲は多少制限されていますが、DateTimeはもっと広い範囲で動作します。 –

4

:あなたはDateTimeオブジェクトとの比較を行うことができます

$date1 = new DateTime("");             
    $date2 = new DateTime("tomorrow"); 

    if ($date2 > $date1) { 
     echo '$date2 is in the future!'; 
    } 

あなたの現在のコードの場合は、これを試してみてください。

$opening_date = new DateTime($current_store['openingdate']); 
$current_date = new DateTime(); 

if ($opening_date > $current_date) { 
    echo '<img id="openingsoon" src="/img/misc/openingsoon.jpg" alt="OPENING SOON" />'; 
} 
関連する問題