Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

php - display hours in half hour range

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

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

1 Reply

0 votes
by (71.8m points)
$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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...