如何在querybuilder中比较两个日期

时间:2015-02-25 17:19:16

标签: php symfony doctrine-orm date-format

我正在尝试创建搜索表单,我需要将所选日期与数据库中的其他日期进行比较。所选日期的格式为(dd / mm / yyyy),数据库中保存的日期格式为(mm-dd-yyy)

$qb = $this->createQueryBuilder('t')
        ->leftJoin('t.image', 'i')->addSelect('i')
        ->leftJoin('t.country', 'country')->addSelect('country')
        ->leftJoin('t.destination', 'destination')->addSelect('destination')
        ->leftJoin('t.airport', 'airport')->addSelect('airport')
        ->Where('t.agence = :agence')
        ->setParameter('agence', $agence);
   //.........

    if (!empty($departureDate)) {
        $qb->andWhere('t.departureDate <= :departureDate')
            ->setParameter('departureDate', new \Datetime($departureDate));
    }
return $qb;

如果所选日期为 13

,则此查询会显示此错误
DateTime::__construct() [<a href='datetime.--construct'>datetime.--construct</a>]: Failed 
to parse time string (13/02/2015) at position 0 (1): Unexpected character

如果少于13 ,查询不会给我正确的结果

3 个答案:

答案 0 :(得分:0)

您的国际化配置错误:您的日期解析为mm/dd/yyyy。您需要更改此行为:

$departureDate = new \DateTime::createFromFormat('dd/mm/YY', $departureDate)

答案 1 :(得分:0)

检查一下 $departureDate = new \DateTime::createFromFormat('d/m/Y', $departureDate)->format('m-d-Y');

答案 2 :(得分:0)

我通过设置这样的查询来解决它:

if (!empty($departureDate)) {
        $date = new \DateTime;
        $qb->andWhere('t.departureDate <= :departureDate')
            ->setParameter('departureDate', $date->createFromFormat('d/m/Y',$departureDate));
    }