Skip to content
Advertisement

Compare dates between datetimes with Doctrine

I have a Symfony2 application with a table that contains a date field, whose type is DateTime.
I need to get all the entities where that field value is now.

If I uses the following code, I get 0 results because Doctrine is comparing the DateTime object.

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

I need to only compare year, month, and day, not hours.

How can I achieve this?

Advertisement

Answer

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;
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement