Skip to content
Advertisement

How to show a list in a time interval in PHP

How to show a list in a time interval in PHP

For example: from 00: 00h to 15: 30h on a specific day. I try it this way:

I spend 15h and 30 minutes from 00:00 on the same day. The idea is to show the list between these hours. I’m wrong about something?

$todayMidday = new DateTime('now');
$todayMidday->sub(new DateInterval('PT15H30M'));

return $this->createQueryBuilder('b')
    ->andWhere('b.reservationDate <= :today')
    ->andWhere('b.reservationDate >= :today')
    ->orderBy('b.hours', $order)
    ->setParameter('today', $todayMidday->format('Y-m-d'))
    ->setMaxResults($limit)
    ->getQuery()
    ->getResult();

Advertisement

Answer

There are many things wrong with your code. I will try to help as you are new. I do not know why the question was marked down though. The 2 comments so far are not really relevant to your question.

One problem here is the use of “sub” in DateTime and also the fact you only have 1 DateTime object. Finally when you query the database you strip the time completely.

The “sub” function subtracts the interval from the date. So what your code is saying is: “get the current date and time and then subtract 15 hours 30 mins from it now select all records less than or equal to and greater than or equal to today’s date (ignore the time)”

What you want is to have 2 DateTime objects one for the end time and one for the start time. For example:

//get the current date time
$timeFrom = new DateTime();
//now set the time to 00:00
$timeFrom->setTime(0,0,0);

//get the current date time
$timeTo = new DateTime();
//now set the time to 00:00
$timeTo->setTime(15,30,0);

return $this->createQueryBuilder('b')
    ->andWhere('b.reservationDate <= :timeTo')
    ->andWhere('b.reservationDate >= :timeFrom')
    ->orderBy('b.hours', $order)
    ->setParameter('timeTo', $timeTo->format('Y-m-d H:i:s'))
    ->setParameter('timeFrom', $timeFrom->format('Y-m-d H:i:s'))
    ->setMaxResults($limit)
    ->getQuery()
    ->getResult();

There are of course a number of different ways to set the dates/times but the key point to note is that 1 DateTime object can only hold 1 date and time at a time. You can change that date or time by any interval but it will only hold that 1 new time. It does not hold a range.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement