Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 373
randomuser3 Avatar asked Mar 04 '26 17:03

randomuser3


1 Answers

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

like image 97
John Conde Avatar answered Mar 07 '26 06:03

John Conde



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!