PHP - 使用DateTime对象确定日期是否在将来

时间:2013-02-26 15:14:54

标签: php datetime

我正在尝试使用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" />';
}

问题是它始终是正面的,所以图像显示它不应该是什么时候。

我必须做一些愚蠢的事,但是它是什么,它让我疯了!

4 个答案:

答案 0 :(得分:62)

这比你想象的要容易。您可以与DateTime个对象进行比较:

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

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

答案 1 :(得分:9)

您不需要DateTime对象。试试这个:

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

答案 2 :(得分: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" />';
}

答案 3 :(得分:3)

$opening_date = new DateTime('2018-07-04');
$current_date = new DateTime();

   if ($opening_date > $current_date) {
      echo "future date";
   }