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

mar*_*n87 23 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" />';
}
Run Code Online (Sandbox Code Playgroud)

问题是它总是积极的,所以图像显示它不应该是什么时候.

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

Joh*_*nde 64

它比你想象的容易.您可以与DateTime对象进行比较:

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

if ($opening_date > $current_date)
{
  // not open yet!
}
Run Code Online (Sandbox Code Playgroud)


d4r*_*nc3 9

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

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

  • 您使用DateTime对象,因为它更好*,不是因为任何其他原因.`strtotime()`的范围有些限制,但DateTime可以在更广泛的范围内工作. (6认同)

Kae*_*uCT 5

您可以将DateTime对象与通常的比较运算符进行比较:

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

  if ($date2 > $date1) {
      echo '$date2 is in the future!';
  }
Run Code Online (Sandbox Code Playgroud)

对于您当前的代码,请尝试以下操作:

$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" />';
}
Run Code Online (Sandbox Code Playgroud)