增加分钟到最近的15分钟间隔

时间:2015-05-16 12:22:39

标签: php date datetime intervals

我想我差不多了 - 尝试获取当前时间然后再添加一个小时然后将选项输出到15分钟间隔 - 所以如果它是14:12,则第一个可用插槽将是14:15然后每个15分钟,直到我的结束时间

$start  = new DateTime("Now");
$start->add(new DateInterval('PT1H'));

$end          = new DateTime("2015-05-16 17:00");
$interval     = new DateInterval('PT15M');
$period       = new DatePeriod($start, $interval, $end);
$current_date = date('d-M-Y g:i:s A');
$current_time = strtotime($current_date);


foreach ($period as $dt)
{
    echo $dt->format('H:i')."<br>";
}

3 个答案:

答案 0 :(得分:2)

您可以将数字钳位到15的下一个倍数,如下所示:

ceil($num / 15) * 15

如上所述调整$start日期。例如:

$start   = new DateTime("today 14:12"); // 2015-05-16 14:12:00
$hour    = (int) $start->format("H");   // 14
$minute  = (int) $start->format("i");   // 12
$clamped = ceil($minute / 15) * 15;     // 15
$start->setTime($hour, $clamped);       // 2015-05-16 14:15:00

setTime注意:超出范围的值会添加到其父值中。

答案 1 :(得分:0)

我假设你的问题是如何在第15分钟到达正确的位置?

这可以解决您的问题吗?:

<?php

$start          = new DateTime("Now");
$currentMinutes = $start->format('i');

if ($currentMinutes > 15) {
    $start->setTime(($start->format('H') + 1), 15);
} elseif($currentMinutes < 15) {
    $start->setTime($start->format('H'), 15);
}

$end          = new DateTime("2015-05-16 17:00");
$interval     = new DateInterval('PT15M');
$period       = new DatePeriod($start, $interval, $end);
$current_date = date('d-M-Y g:i:s A');
$current_time = strtotime($current_date);


foreach ($period as $dt)
{
    echo $dt->format('H:i')."<br>";
}

或者如果您喜欢简短:

$start          = new DateTime("2015-05-16 13:15");
$currentMinutes = $start->format('i');
$currentHour    = $start->format('H');
$start->setTime(($currentMinutes > 15 ? ++$currentHour : $currentHour), 15);
[...]

答案 2 :(得分:-1)

$min15InSecs = 15*60;
$min15 = time()-(time()%$min15InSecs)+$min15InSecs;

$start  = new DateTime(date("Y-m-d H:i", $min15));
$start->add(new DateInterval('PT1H'));

$end  = new DateTime("2015-05-16 19:00");
$interval = new DateInterval('PT15M');
$period   = new DatePeriod($start, $interval, $end);
$current_date = date('d-M-Y g:i:s A');
$current_time = strtotime($current_date);


foreach ($period as $dt)
{

    echo $dt->format('H:i')."<br>";
}