我正在尝试确定日期是否在未来,使用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" />';
}
问题是它总是正的,所以图像在不应该显示的时候显示。
我一定是做了什么蠢事,但它是什么,它把我逼疯了!这比你想象的要容易。你可以对DateTime对象进行比较:
$opening_date = new DateTime($current_store['openingdate']);
$current_date = new DateTime();
if ($opening_date > $current_date)
{
// not open yet!
}
您不需要DateTime
对象。试试这个:
$now = time();
if(strtotime($current_store['openingdate']) > $now) {
// then it is in the future
}
您可以将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" />';
}
$opening_date = new DateTime('2018-07-04');
$current_date = new DateTime();
if ($opening_date > $current_date) {
echo "future date";
}