'PHP add 45 Minutes to a Time with Loop [duplicate]
I'm preparing an appointment script for entering visiting start hours and end hours like 09:00 and 20:00 and each visit period is 45 minutes.
I want to add 45 minutes from start time to end time within a loop. But with samples on internet I couldn't do it.
Visiting times are dynamic I mean it could be 09:00-20:00 or 11:00-23:00 etc.
The exact solution I'm trying to do is:
$visit_start = '09:00';
$visit_end = '20:00';
$difference = $visit_end - $visit_start;
$i = 1;
while( $i <= $difference )
{
print $visit_hour_list = $visit_start + 45;
$i++;
}
and the print out will be like:
09:00
09:45
10:30
11:15
12:00
until to end hour. But I have no clue how that could work.
Solution 1:[1]
As already answered in the similar question "How can I get a range of dates in php?", you can make use of the DatePeriod class in PHP to iterate over each 45 minute times' between a start and end time:
Demo:
<?php
/**
* PHP add 45 Minutes to a Time with Loop
*
* @link https://stackoverflow.com/a/19399907/367456
*/
$begin = new DateTime("09:00");
$end = new DateTime("20:00");
$interval = DateInterval::createFromDateString('45 min');
$times = new DatePeriod($begin, $interval, $end);
foreach ($times as $time) {
echo $time->format('H:i'), '-',
$time->add($interval)->format('H:i'), "\n"
;
}
Output:
09:00-09:45
09:45-10:30
10:30-11:15
11:15-12:00
12:00-12:45
12:45-13:30
13:30-14:15
14:15-15:00
15:00-15:45
15:45-16:30
16:30-17:15
17:15-18:00
18:00-18:45
18:45-19:30
19:30-20:15
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Community |
