在php中比较日期的功能不起作用

时间:2017-09-09 11:38:33

标签: 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);
        $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;
           }
        }

我如何称呼它:

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

日期格式:

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

它在beginnig中停止:

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

2 个答案:

答案 0 :(得分:2)

这样的事情应该有效:

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);
}

希望这有帮助!

答案 1 :(得分:1)

可能你有其他命名空间。因此,当您在不同的命名空间

中时,需要在全局方法/类之前添加\

请参阅此处的文档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);