user3396420
user3396420

Reputation: 840

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?

Upvotes: 28

Views: 67429

Answers (3)

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

Upvotes: 5

goto
goto

Reputation: 8164

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

Upvotes: 67

Nicolai Fröhlich
Nicolai Fröhlich

Reputation: 52483

There is a difference between the date and datetime types in doctrine.

date: Type that maps a SQL DATETIME to a PHP DateTime object.

datetime: Type that maps a SQL DATETIME/TIMESTAMP to a PHP DateTime object.

Make sure you have set the column type to date instead of datetime.

Alternatively - as a workaround - you could get the day from the original date1 and then search between a same-day date2 -> 00:00:00 and same-day date3 -> 23:59:59 using a custom repository method.

Upvotes: 2

Related Questions