3

I need to compare the time difference between "todays date and time" and two dates in the future. These dates are including time informations, too.

At the moment I'm having the problem that the "if condition" doesn't output the expected result.

That's the code and the live example:

$date_a = new DateTime('now');

$date_b2 = new DateTime('wednesday + 7 day 08:00');
$date_c2 = new DateTime('saturday + 7 day 20:00');

$intervaln = date_diff($date_a,$date_b2);
$interval2n = date_diff($date_a,$date_c2);

$diff1n = $intervaln->format('%d d. %h h. %i min.');
$diff2n = $interval2n->format('%d d. %h h. %i min.');

    if ($diff1n > $diff2n) {
      echo $diff1n;
    } 
    else if ($diff1n < $diff2n) {
       echo $diff2n;
    }

As you see it outputs the second condition but it should be the first one since $diff1n has the bigger time difference than $diff2n.

What's the right way to compare these dates and times to each other?

Berstos
  • 179
  • 10
  • 1
    https://stackoverflow.com/questions/9547855/are-php-dateinterval-comparable-like-datetime/28700874 might be of some help – aynber Jul 07 '21 at 12:51

2 Answers2

0

Try strtotime() on the times .

$diff1n = $intervaln->format('%d d. %h h. %i min.');
$diff2n = $interval2n->format('%d d. %h h. %i min.');
$d1=strtotime($diff1n);
$d2=strtotime($diff2n);
if ($d1> $d2) {
  echo $diff1n;
} 
else if ($d1< $d2) {
   echo $diff2n;
}
Chris Ngure
  • 50
  • 1
  • 7
0

You can convert the dates to timestamp using the setTimestamp() function, then get the difference between the two, divide it by no of seconds that make a day round of to .2 float and print it like "2 days from now" then compare it to the no. of days i.e

// $diffdateAandNowtime is the difference between the uni time of dateA and nowtime

// $diffdateBandNowtime is the difference between the uni time of dateB and nowtime

    $diffdateAandNowtime  = 4600; 
    $diffdateBandNowtime  = 5600; 
    
    $nowtime = 36000;
    
    //time here is in seconds
    
        if( $diffdateAandNowtime > $diffdateBandNowtime )
        {
        //run some code here
     echo $diffdateAandNowtime;
 
        }
        elseif( $diffdateBandNowtime > $diffdateAandNowtime )
        {
    
    echo $diffdateAandNowtime;

        }

refer here for setTimestamp()

klinsman Agam
  • 80
  • 1
  • 2