PHP代码修正时间间隔添加

时间:2017-09-28 10:59:08

标签: php

这是我当前的代码,下面是此代码的输出。但我需要对此进行一些修正。

$startTimeInterval = 15;
$duration = 20;
$open = '2017-09-29T10:00:00-05:00';
$close = '2017-09-29T17:30:00-05:00';

$startTimeInterval = $startTimeInterval.' minutes';
$interval = DateInterval::createFromDateString($startTimeInterval);
$begin = new DateTime($open);
$end = new DateTime($close);
$end->add($interval);

$periods = iterator_to_array(new DatePeriod($begin, $interval, $end));

$start = array_shift($periods);
$slot = array();
foreach ($periods as $time) {
    $slot[]= $start->format('h:iA'). ' - '. $time->format('h:iA');
    $start = $time;
}
echo '<pre>';print_r($slot);exit;

输出

[0] => 10:00AM - 10:15AM
[1] => 10:15AM - 10:30AM
[2] => 10:30AM - 10:45AM
[3] => 10:45AM - 11:00AM
[4] => 11:00AM - 11:15AM
........
[28] => 05:00PM - 05:15PM
[29] => 05:15PM - 05:30PM

我需要这个

[0] => 10:00AM - 10:20AM
[1] => 10:15AM - 10:35AM
[2] => 10:30AM - 10:50AM
[3] => 10:45AM - 11:05AM
[4] => 11:00AM - 11:20AM
........
[28] => 05:00PM - 05:20PM
[29] => 05:15PM - 05:35PM

水平,它将添加持续时间,垂直方向将添加startTimeInterval

1 个答案:

答案 0 :(得分:0)

也许这是一个解决方案:

您的$time类型为DateTime

您可以clone $time并在循环中添加5分钟。

例如:

foreach ($periods as $time) {
    $clonedTime = clone $time;
    $clonedTime->modify('+5 minutes');

    $slot[]= $start->format('h:iA'). ' - '. $clonedTime->format('h:iA');
    $start = $time;
}

将导致:

Array
(
    [0] => 10:00AM - 10:20AM
    [1] => 10:15AM - 10:35AM
    [2] => 10:30AM - 10:50AM
    [3] => 10:45AM - 11:05AM
    [4] => 11:00AM - 11:20AM
    [5] => 11:15AM - 11:35AM
    [6] => 11:30AM - 11:50AM
    [7] => 11:45AM - 12:05PM
    [8] => 12:00PM - 12:20PM
    [9] => 12:15PM - 12:35PM
    [10] => 12:30PM - 12:50PM
    [11] => 12:45PM - 01:05PM
    [12] => 01:00PM - 01:20PM
    [13] => 01:15PM - 01:35PM
    [14] => 01:30PM - 01:50PM
    [15] => 01:45PM - 02:05PM
    [16] => 02:00PM - 02:20PM
    [17] => 02:15PM - 02:35PM
    [18] => 02:30PM - 02:50PM
    [19] => 02:45PM - 03:05PM
    [20] => 03:00PM - 03:20PM
    [21] => 03:15PM - 03:35PM
    [22] => 03:30PM - 03:50PM
    [23] => 03:45PM - 04:05PM
    [24] => 04:00PM - 04:20PM
    [25] => 04:15PM - 04:35PM
    [26] => 04:30PM - 04:50PM
    [27] => 04:45PM - 05:05PM
    [28] => 05:00PM - 05:20PM
    [29] => 05:15PM - 05:35PM
)