Search code examples
phpdatetimedate-arithmetic

Why I can't successfully subtract two datetime values in php?


I have the following code:

echo "first row " . $firstRow["begin_date"];
echo " super beg " . $superbegintime; 
echo " duration " . $duration;
if(($firstRow["begin_date"] - $superbegintime) >= $duration)
{
    echo "it works!";
}

$firstRow["begin_date"] is a DATETIME type field taken from database

$superbegintime is created as follows:

$date = new DateTime();
$superbegintime= $date->add(DateInterval::createFromDateString('10 minutes'))->format('Y-m-d H:i:s');

and $duration is a field $duration = 15; that should represent number of seconds.

I cannot enter the if statement and print the it works! message, what am I doing wrong here?


Solution

  • You are comparing and doing math with strings which can be problematic and not get you the right results especially when you compare them to integers (and don't specify what that number actually means). DateTime objects allow you to do the math and then compare the difference with the duration. The difference and the duration are both DateInterval objects which are comparable.

    $beginDate      = new DateTime($firstRow["begin_date"]);
    $superbegintime = new DateTime($superbegintime); 
    $duration       = DateInterval::createFromDateString('15 seconds');
    $diff = $beginDate->diff($superbegintime);
    
    if($diff >= $duration)
    {
        echo "it works!";
    }
    

    Demo