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?
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.
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.
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; }
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]; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With