Compare dates between datetimes with Doctrine

后端 未结 3 482
萌比男神i
萌比男神i 2021-01-01 15:05

I have a Syfmony2 app with a table which has a date field. This date field is a DateTime type.

I need to get all the entities which the same date as now.

But

3条回答
  •  佛祖请我去吃肉
    2021-01-01 15:29

    I see this simple way:

    $now = new \DateTime();
    
    $data = $entityRepository->getByDate($now);
    

    then in your repository

    public function getByDate(\Datetime $date)
    {
        $from = new \DateTime($date->format("Y-m-d")." 00:00:00");
        $to   = new \DateTime($date->format("Y-m-d")." 23:59:59");
    
        $qb = $this->createQueryBuilder("e");
        $qb
            ->andWhere('e.date BETWEEN :from AND :to')
            ->setParameter('from', $from )
            ->setParameter('to', $to)
        ;
        $result = $qb->getQuery()->getResult();
    
        return $result;
    }
    

提交回复
热议问题