0

I am trying to pass a message if the set time has passed. I have two variables the $date1 which is the current time and the $date2 which is the target time. The third variable $interval is the difference between the two times.

The challenge I am having is that I can't get the code to work when time has passed. It works properly if the target time $date2 is ahead of the current time $date1.

date_default_timezone_set('Africa/Nairobi');
$date1 = new DateTime();
$date2 = new DateTime("$closing_date"); //Closing date 09-03-2021 13:00
$interval = $date1->diff($date2);

//PHP Code
add_filter('the_content', 'hide_post_contents');

function hide_post_contents( $content ) {
   if(( $interval->h = 0 ) && ( $interval->i <=0 )) {
        return '<h3>This content is no longer available</h3>
        <p>Please feel free to check out other content.</p>';
    }
    return $content;
}

I noticed that even after the time has passed, the time passed is not treated as negative value. Thanks

Danstan Ongubo
  • 105
  • 1
  • 8
  • You can directly compare `DateTime` objects, no need to calculate the diff. `$date2 < $date1` should do the trick. – El_Vanja Mar 09 '21 at 14:14
  • 1
    Does this answer your question? [How do I compare two DateTime objects in PHP 5.2.8?](https://stackoverflow.com/questions/961074/how-do-i-compare-two-datetime-objects-in-php-5-2-8) – El_Vanja Mar 09 '21 at 14:16
  • Even though the duplicate specifically refers to an outdated version of PHP, the answers still hold value. – El_Vanja Mar 09 '21 at 14:16
  • $date2 < $date1 doesn't work either. This doesn't do the difference which is also good but the time difference is not negative. So there is no way of detecting whether ```$date2``` is greater than ```$date1``` – Danstan Ongubo Mar 09 '21 at 14:19
  • If it doesn't work, then something else is at fault here. Check the code [here](https://3v4l.org/I5q4R). – El_Vanja Mar 09 '21 at 14:24
  • convert your `$date1` and `$date2` into time then try comparing it using `strtotime()` – Basharmal Mar 09 '21 at 14:59

1 Answers1

0

You can compare the time in PHP like below

date_default_timezone_set('Africa/Nairobi');
$currentdatetime = date("Y-m-d h:i:sa");
$date1 = strtotime($currentdatetime);

$closingdate = date("2021-03-09 13:00:00"); //in this format Y-m-d h:i:sa
$date2 = strtotime($closingdate);
if($date1 > $date2)
{
echo "current date  $date1 is grater than $date2";
}
else{
echo "current date  $date1 is less than $date2";

}
Basharmal
  • 1,313
  • 10
  • 30