Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Determine if the date is in the future using DateTime Object

Tags:

php

datetime

I am trying to determine whether a date is in the future or not, using DateTime objects but it always comes back positive:

$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!

like image 971
martincarlin87 Avatar asked Feb 26 '13 15:02

martincarlin87


People also ask

How can check if condition in date in PHP?

we can analyze the dates by simple comparison operator if the given dates are in a similar format. <? php $date1 = "2018-11-24"; $date2 = "2019-03-26"; if ($date1 > $date2) echo "$date1 is latest than $date2"; else echo "$date1 is older than $date2"; ?>

What is Z in date format PHP?

The difference between P and p format is that the new p format uses Z for UTC time, while the P format uses +00:00 . The ISO 8601 date format permits UTC time with +00:00 format, or with Z . This means both date formats below are valid: 2020-09-09T20:42:34+00:00.


2 Answers

It's easier than you think. You can do comparisons with DateTime objects:

$opening_date = new DateTime($current_store['openingdate']); $current_date = new DateTime();  if ($opening_date > $current_date) {   // not open yet! } 
like image 117
John Conde Avatar answered Sep 28 '22 09:09

John Conde


You don't need a DateTime object for this. Try this:

$now = time();
if(strtotime($current_store['openingdate']) > $now) {
     // then it is in the future
}
like image 44
d4rkpr1nc3 Avatar answered Sep 28 '22 08:09

d4rkpr1nc3