1

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");
}
limio
  • 25
  • 4
  • An error you say? So what error are you getting please – RiggsFolly Mar 02 '22 at 17:22
  • 1
    What is `$start_time`? You have `$start` defined, but it's a string, not a DateTime object, and you don't show if/where `$start_time` or `$end_time` is defined. – aynber Mar 02 '22 at 17:22
  • If you are going to use examples, then you cannot mix and match bits of the examples you found – RiggsFolly Mar 02 '22 at 17:24
  • @RiggsFolly plz check the updated question – limio Mar 02 '22 at 17:25
  • `$start` and `$end` are strings, not DateTime objects. Therefore, you cannot use `date()` or `modify()` on them – aynber Mar 02 '22 at 17:25
  • Please check the multiple answers in the link you gave us – RiggsFolly Mar 02 '22 at 17:25
  • The accepted answer in the Question you link to need only the SMALLEST change to work for you `$interval = DateInterval::createFromDateString('30 minute');` – RiggsFolly Mar 02 '22 at 17:28
  • @aynber How can i do it? – limio Mar 02 '22 at 17:29
  • @RiggsFolly I tried like that. Its giving this error`Uncaught TypeError: DatePeriod::__construct() accepts (DateTimeInterface, DateInterval, int [, int]), or (DateTimeInterface, DateInterval, DateTime [, int]), or (string [, int]) as arguments` – limio Mar 02 '22 at 17:31

1 Answers1

2

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:i\n");
}

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:i\n");
}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149