Select Entries Between Dates in Doctrine 2

Select entries between dates in doctrine 2

You can do either…

$qb->where('e.fecha BETWEEN :monday AND :sunday')
->setParameter('monday', $monday->format('Y-m-d'))
->setParameter('sunday', $sunday->format('Y-m-d'));

or…

$qb->where('e.fecha > :monday')
->andWhere('e.fecha < :sunday')
->setParameter('monday', $monday->format('Y-m-d'))
->setParameter('sunday', $sunday->format('Y-m-d'));

Doctrine - query with date range

It appears to me that you have used format in your from and to dates, which you don't need to. Also, I have noticed that the same $date has been used for both from and to. I am sure you didn't mean to use like that.

Replace this,

 ->setParameter('from', $date->format('Y-m-d H:i:s'))
->setParameter('to', $date->format('Y-m-d H:i:s'))

with this,

$dateFrom = new \Datetime();
$dateFrom->setDate(2017, 1, 31);

$dateTo = new \Datetime();
$dateTo->setDate(2017, 12, 31);

->setParameter('from', $dateFrom )
->setParameter('to', $dateTo)

Hope this helps.

Cheers.

Select entries where now between startDate and endDate

$repository = $this->getDoctrine()->getRepository('AppBundle:Product');

$qb = $repository->createQueryBuilder('c')
->where('c.startDate < :now')
->andWhere('c.endDate > :now')
->setParameter('now', new \Datetime())
->orderBy('c.id', 'DESC');

return $qb->getQuery()->getResult();

Compare dates between datetimes with Doctrine

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


Related Topics



Leave a reply



Submit