我想在开始时间和结束时间之间划分相同的时间段。
Php功能:
public function time_slot_time() {
$startTimeInterval = '15';
$open = '2017-08-23T1:00:00-05:00';
$close = '2017-08-23T5:00:00-05:00';
// Logic
}
输出:
1:00PM - 1:15PM
1:15PM - 1:30PM
1:30PM - 1:45PM
1:45PM - 2:00PM
2:00PM - 2:15PM
...
3:15PM - 3:30PM
3:30PM - 4:45PM
4:45PM - 5:00PM
答案 0 :(得分:3)
PHP提供了一组非常丰富的函数来处理日期和时间,请参阅http://php.net/manual/en/book.datetime.php
在这种情况下,DateTime
,DateInterval
和DatePeriod
类都非常有用:
<?php
$interval = DateInterval::createFromDateString('15 minutes');
$begin = new DateTime('2017-08-23T1:00:00-05:00');
$end = new DateTime('2017-08-23T5:00:00-05:00');
// DatePeriod won't include the final period by default, so increment the end-time by our interval
$end->add($interval);
// Convert into array to make it easier to work with two elements at the same time
$periods = iterator_to_array(new DatePeriod($begin, $interval, $end));
$start = array_shift($periods);
foreach ($periods as $time) {
echo $start->format('H:iA'), ' - ', $time->format('H:iA'), PHP_EOL;
$start = $time;
}
DatePeriod
实现了PHP的Traversable接口,这意味着你可以像数组一样循环它(或者只是将它转换为一个,在这种情况下)。
答案 1 :(得分:1)
public function time_slot_time() {
$startTimeInterval = 15*60;
$open = strtotime('2017-08-23T1:00:00-05:00');
$close = strtotime('2017-08-23T5:00:00-05:00');
do{
echo date('H:i',$open).' - '.date('H:i',$open+$startTimeInterval). ' <br/>';
$open = $open+$startTimeInterval;
}while($open<$close);
}
我的逻辑是简单地走过时间段并回应它们......没什么好看的。肯定有更好的方法,但它应该足够简单,你可以围绕它构建。