Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am working on an appointment script that takes office opening and closing hours from database and then displays the time in between the opening and closing hours to book for a meeting, each meeting can only be booked for half an hour, so i need to display timings like this using a radio button

9:00am  - 9:30am
9:30am  - 10:00am
10:00am - 10:30am
...
...
...

I am able to calculate the total number of hours office is open, and using for loop i am able to display the timings

$office_start_time = '09:00:00';
$office_end_time = '16:00:00';

$start = explode(':', $office_start_time);
$end = explode(':', $office_end_time);
$total_hours = $end[0] - $start[0] - ($end[1] < $start[1]);
echo 'total hours: '.$total_hours;
echo '<br>';
//exit;
?>
<table class="table table-hover table-bordered">
    <tbody>
    <?php for ($i = 0; $i < $total_hours; $i++) {
        echo "<input name='time' type='radio' value='09:00|09:30'> 9:00am-9:30am<br/>";
        ?>

    <?php } ?>
    </tbody>
</table>

my problem is the above code gives me an output like below and I am stuck at how to go about getting the right outcome

enter image description here

I will really appreciate if i can get some help on displaying the timings as below

9:00am  - 9:30am
9:30am  - 10:00am
10:00am - 10:30am
...
...
...
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
468 views
Welcome To Ask or Share your Answers For Others

1 Answer

$start    = new DateTime('09:00:00');
$end      = new DateTime('16:00:01'); // add 1 second because last one is not included in the loop
$interval = new DateInterval('PT30M');
$period   = new DatePeriod($start, $interval, $end);

$previous = '';
foreach ($period as $dt) {
    $current = $dt->format("h:ia");
    if (!empty($previous)) {
        echo "<input name='time' type='radio' value='{$previous}|{$current}'> {$previous}-{$current}<br/>";
    }
    $previous = $current;
}

See it in action


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...