我正在制作一个约会脚本,从数据库开始和关闭时间,然后显示开始和结束时间之间的时间预订会议,每次会议只能预订半小时,所以我需要使用单选按钮显示这样的时间
9:00am - 9:30am
9:30am - 10:00am
10:00am - 10:30am
...
...
...
我可以计算办公室开放的总小时数,并使用for循环我可以显示时间
$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>
我的问题是上面的代码给了我一个类似下面的输出,我坚持如何获得正确的结果
如果我能在下面显示时间方面得到一些帮助,我将非常感激
9:00am - 9:30am
9:30am - 10:00am
10:00am - 10:30am
...
...
...
答案 0 :(得分:5)
$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;
}
答案 1 :(得分:4)
strtotime
魔术可以做到这一点
$start = '09:00:00';
$end = '16:00:00';
$time = strtotime($start);
$timeStop = strtotime($end);
while($time<$timeStop) {
echo date('H:i', $time);
$time = strtotime('+30 minutes', $time);
echo ' - ' . date('H:i', $time) . '<br/>';
}
结果:
09:30 - 10:00
10:00 - 10:30
10:30 - 11:00
11:00 - 11:30
11:30 - 12:00
12:00 - 12:30
12:30 - 13:00
13:00 - 13:30
13:30 - 14:00
14:00 - 14:30
14:30 - 15:00
15:00 - 15:30
15:30 - 16:00
答案 2 :(得分:0)
怎么样
<?php
for ($i = 0; $i < $total_hours; $i++)
{
$time = $start[0] + $i;
echo "<input name='time' type='radio' value='0" . $time . ":00|0" . $time . ":30'> " . $time . ":00am-" . $time . ":30am<br/>";
}
?>