I use a "DateInterval" with an interval of 3 hours to get all the dates between a start and end time. The result looks like that:
15:00 | 18:00 | 21:00 | 00:00 | 03:00 (and so on...)
Now I’m searching a solution that only the next "DateInterval" value gets shown (depending on the actual time), and not all of them.
Example: if the actual time is 19:29
the shown result should be 21:00
.
My code so far:
$start = new DateTime('2022-12-18 15:00:00');
$interval = DateInterval::createFromDateString('3 hours');
$end = new DateTime('2022-12-31 15:00:00');
$occurrences = new DatePeriod($start, $interval, $end);
foreach ($occurrences as $occurrence) {
echo $occurrence->format('H:i') . PHP_EOL;
}
2
Answers
No need to iterate through the period. Just manipulate current hour number.
This probably might be reworked with plain unix timestamps for even simplier code:
UPDATE: for dynamic start time, when the hour is not x3
The following will properly take into account the start time and return an object with the same timezone and other properties as its input.
Output: