30

我正在尝试使用对象确定日期是否在未来,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

4 回答 4

81

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

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

if ($opening_date > $current_date)
{
  // not open yet!
}
于 2013-02-26T15:18:54.277 回答
10

你不需要一个DateTime对象。试试这个:

$now = time();
if(strtotime($current_store['openingdate']) > $now) {
     // then it is in the future
}
于 2013-02-26T15:17:54.540 回答
5

您可以将 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" />';
}
于 2013-02-26T15:20:50.307 回答
4
$opening_date = new DateTime('2018-07-04');
$current_date = new DateTime();

   if ($opening_date > $current_date) {
      echo "future date";
   }
于 2018-07-03T03:14:37.500 回答