Search code examples
phpdatetimetimephp-5.4date-difference

DateTime object declaration breaks script on PHP 5.4.16


While editing the php file it shows DateTime is not a valid method, plus when I try to use this it stops loading the rest of the page, do I have to implement something?

My goal is to check either if the difference between those variables is more than 3 minutes.

Can I output the difference just in minutes?

$arr["etime"] comes from a mysql query in the format of Y-m-d H:i:s.

$etime = $arr["etime"];
$datenow = date('Y-m-d H:i:s');

$datetimenow = new DateTime($datenow);
$datetimee = new DateTime($etime);
$datedifference = $datetimee->diff($datetimenow);
echo $datedifference->format("%H:%I:%S");

If I just put $date = new DateTime('2000-01-01'); it doesn't load the rest of the page after this.

If I put $datetimenow = new DateTime(); the rest of the page won't load.

Using exception handling, I received:

PHP Fatal error: Uncaught exception 'Exception'

with message:

'DateTime::__construct(): It is not safe to rely on the system's timezone settings. You are required to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone.'


Solution

  • You will only need to check the output object values generated from diff(): (Demo)

    $etime = '2017-07-10 16:59:04';
    $timezone=new DateTimeZone("Australia/Melbourne"); // declare whatever your timezone is
    $datetimee=new DateTime($etime,$timezone);  // resultset datetime
    $datetimenow=new DateTime("now",$timezone); // current datetime
    $diff=$datetimee->diff($datetimenow);
    //var_export($diff);
    if($diff->i>=3 ||$diff->h>0 || $diff->d>0 || $diff->m>0 || $diff->y>0){
        echo "Difference is 3 minutes or more";
    }else{
        echo "Difference is not yet 3 minutes";
    }
    

    If you are still experiencing issues with the DateTime class, it may be time to revert to good-ol' strtotime(). It provides a much simpler bit of code anyhow:

    if(strtotime('now')-strtotime($etime)>179){ // assuming now is always bigger than etime
        echo "Difference is 3 minutes or more";
    }else{
        echo "Difference is not yet 3 minutes";
    }