简体   繁体   中英

Function to compare dates in php doesn't work

I built this function that is supposed to compare dates and return a boolean. When I run it though, it breaks, the page stops.

the function:

 public function compare_date_outlook($creation, $modification) {
        $creation_date =  DateTime::createFromFormat('Y-m-d\TH:i:s+', $creation);
        $creation_date = $creation_date->format( 'Y-m-d');
        $modification_date =  DateTime::createFromFormat('Y-m-d\TH:i:s+', $modification);
        $modification_date = $modification_date->format( 'Y-m-d');   
        $date = new \DateTime( 'yesterday' );
        $date->setTime( 0, 0, 0 );
        $yesterday = $date->format( 'Y-m-d');

           if (($creation || $modification) == $yesterday)
           {
               return TRUE;
           }

           else {
               return FALSE;
           }
        }

How I call it:

if ( compare_date_outlook($a['creationDate'], $a['lastModifiedDate']) === TRUE)

The format of the date:

 $a['creationDate'] = "2017-09-08T13:26:11.4354775Z";

It stops right in the beginnig:

$creation_date =  DateTime::createFromFormat('Y-m-d\TH:i:s+', $creation);

Something like this should work:

function compare_date_outlook($creation, $modification)
{
    $today = (new \Datetime())->setTime(0, 0, 0);
    $yesterday = (new \Datetime('yesterday'))->setTime(0, 0, 0);

    $creation_date = \DateTime::createFromFormat('Y-m-d\TH:i:s+', $creation);
    $modification_date = \DateTime::createFromFormat('Y-m-d\TH:i:s+', $modification);

    return ($creation_date >= $yesterday && $creation_date < $today) ||
        ($modification_date >= $yesterday && $modification_date < $today);
}

Probably you have other namespace. So you need to add \\ before global methods/classes when you are in different namespace

see doc here http://www.php.net/manual/en/language.namespaces.global.php

public function compare_date_outlook($creation, $modification) {
        $creation_date =  \DateTime::createFromFormat('Y-m-d\TH:i:s+', $creation);
        $creation_date = $creation_date->format( 'Y-m-d');
        $modification_date =  \DateTime::createFromFormat('Y-m-d\TH:i:s+', $modification);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM