PHP - 使用 DateTime 对象确定日期是否在未来
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15092639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP - Determine if the date is in the future using DateTime Object
提问by martincarlin87
I am trying to determine whether a date is in the future or not, using DateTimeobjects but it always comes back positive:
我正在尝试使用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" />';
}
The problem is it's always positive so the image shows when it shouldn't be.
问题是它总是积极的,所以图像显示了它不应该出现的时候。
I must be doing something stupid, but what is it, it's driving me insane!
我一定在做一些愚蠢的事情,但这是什么,它让我发疯!
回答by John Conde
回答by d4rkpr1nc3
You don't need a DateTimeobject for this. Try this:
你不需要一个DateTime对象。尝试这个:
$now = time();
if(strtotime($current_store['openingdate']) > $now) {
// then it is in the future
}
回答by KaeruCT
You can compare DateTime objects with the usual comparison operators:
您可以将 DateTime 对象与常用的比较运算符进行比较:
$date1 = new DateTime("");
$date2 = new DateTime("tomorrow");
if ($date2 > $date1) {
echo '$date2 is in the future!';
}
For your current code, try this:
对于您当前的代码,请尝试以下操作:
$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" />';
}
回答by Optimaz ID
$opening_date = new DateTime('2018-07-04');
$current_date = new DateTime();
if ($opening_date > $current_date) {
echo "future date";
}

