Compare dates between datetimes with Doctrine

后端 未结 3 480
萌比男神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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-01 15:37

    Method in repository

    public function getDays(\DateTime $firstDateTime, \DateTime $lastDateTime)
    {
        $qb = $this->getEntityManager()->createQueryBuilder()
            ->select('c')
            ->from('ProjectBundle:Calendar', 'c')
            ->where('c.date BETWEEN :firstDate AND :lastDate')
            ->setParameter('firstDate', $firstDateTime)
            ->setParameter('lastDate', $lastDateTime)
        ;
    
        $result = $qb->getQuery()->getResult();
    
        return $result;
    }
    

    And action

    public function calendarAction()
    {
        $currentMonthDateTime = new \DateTime();
        $firstDateTime = $currentMonthDateTime->modify('first day of this month');
        $currentMonthDateTime = new \DateTime();
        $lastDateTime = $currentMonthDateTime->modify('last day of this month');
    
        $days = $this->getDoctrine()
            ->getRepository('ProjectBundle:Calendar')
            ->getDays($firstDateTime, $lastDateTime);
    
        return ['days' => $days];
    }
    

提交回复
热议问题