Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare dates between datetimes with Doctrine

Tags:

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?

like image 935
user3396420 Avatar asked Apr 28 '15 11:04

user3396420


People also ask

How do I compare two Datetimes in Python?

Use the strptime(date_str, format) function to convert a date string into a datetime object as per the corresponding format . To get the difference between two dates, subtract date2 from date1. A result is a timedelta object.

How can I compare two Datetimes in JavaScript?

In JavaScript, we can compare two dates by converting them into numeric values to correspond to their time. First, we can convert the Date into a numeric value by using the getTime() function. By converting the given dates into numeric values we can directly compare them.


2 Answers

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; } 
like image 64
goto Avatar answered Sep 24 '22 23:09

goto


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]; } 
like image 32
Дмитрий Будницкий Avatar answered Sep 21 '22 23:09

Дмитрий Будницкий