Skip to content
Advertisement

get time intervals with time range

I am trying to get time interval with custom start and end time variables for which i have searched and find its relevant information on this link.

I have tried the following code but its giving errorUncaught Error: Call to a member function date() on string

$start = date("H:i",strtotime('08:30 AM'));
$end = date("H:i",strtotime('06:00 PM'));
for($i = $start; $i <= $end; $i->modify(' +30 MINUTE')){
    echo $i->date("H:i");
}

Advertisement

Answer

You need to use the builtin DateTime class and the DateInterval class as well

$begin = new DateTime('08:30:00');
$end = new DateTime('12:45:00');

$interval = DateInterval::createFromDateString('30 minute');
$period = new DatePeriod($begin, $interval, $end);

foreach ($period as $dt) {
    echo $dt->format("H:in");
}

RESULTS

08:30
09:00
09:30
10:00
10:30
11:00
11:30
12:00
12:30

And if the time roles over to another day something like this

$begin = new DateTimeImmutable('2022-03-01 16:00:00');
$end = (new DateTime())->createFromImmutable($begin)->add(new DateInterval('P1D'))->settime(8,30,0);

$interval = DateInterval::createFromDateString('30 minute');
$period = new DatePeriod($begin, $interval, $end);

foreach ($period as $dt) {
    echo $dt->format("d/m/Y H:in");
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement