如何在查询生成器中比较两个日期

How to compare two date in querybuilder

我正在尝试创建一个搜索表单,我需要将所选日期与数据库中的其他日期进行比较。所选日期的格式为 (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 ,查询不会给我正确的结果

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

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

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

我已经通过设置查询解决了这个问题:

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