Php - compare two future dates distance from current date

71 Views Asked by At

I'm trying to change $showThis based on whichever date is closest to now. How can I compare the time differences? Currently $interval1 > $interval2 does not work. I know the difference is being calculated, but I'm not sure how to compare the two.

$currentTime = new DateTime("now");
$wednesday = new DateTime('wednesday 10:59pm');
$saturday = new DateTime('saturday 10:59pm');
$interval1 = $currentTime->diff($wednesday);
$interval2 = $currentTime->diff($saturday);

if($interval1 > $interval2){
    $showThis = $saturday->format('D m/d/Y h:i A');
}
if($interval1 < $interval2){
    $showThis = $wednesday->format('D m/d/Y h:i A');
}
2

There are 2 best solutions below

0
On BEST ANSWER

Use getTimestamp method.

$interval1 = $wednesday->getTimestamp() - $currentTime->getTimestamp();
$interval2 = $saturday->getTimestamp() - $currentTime->getTimestamp();
0
On

You should convert the interval into seconds by adding it to 0 date before comparing them:

$currentTime = new DateTime("now");
$wednesday = new DateTime('wednesday 10:59pm');
$saturday = new DateTime('saturday 10:59pm');

$interval1 = $currentTime->diff($wednesday);
$interval2 = $currentTime->diff($saturday);

$seconds1 = date_create('@0')->add($interval1)->getTimestamp();
$seconds2 = date_create('@0')->add($interval2)->getTimestamp();

if ($seconds1 > $seconds2){
    $showThis = $saturday->format('D m/d/Y h:i A');
}
else {
    $showThis = $wednesday->format('D m/d/Y h:i A');
}

echo $showThis;