舍入到PHP中最近的可用时隙

时间:2012-03-01 20:42:10

标签: php date rounding

我一直在努力工作一个小时左右,并且空白了。基本上我需要花费当前时间,增加30分钟,然后再进行下一个15分钟。

示例:

  • 如果现在是20:00,结果= 20:45
  • 如果现在是20:10,结果= 20:45
  • 如果它现在是20:16,结果= 21:00
  • 如果它现在是20:35,结果= 21:15

我的PHP生疏了,我一直在混淆日期添加和循环方法试图让这个工作,我知道这很简单 - 只是用完了想法!

由于

4 个答案:

答案 0 :(得分:6)

我也会添加一个解决方案:

<?php

date_default_timezone_set('America/Los_Angeles');

$times = array();
$times[] = strtotime('00:07');
$times[] = strtotime('04:21');
$times[] = strtotime('20:00');
$times[] = strtotime('20:10');
$times[] = strtotime('20:16');
$times[] = strtotime('20:35');
$times[] = strtotime('23:15');


foreach($times as $time) {
    echo date('m-d-Y H:i', $time) . ' becomes ' . date('m-d-Y H:i:s', roundToNearestInterval($time)) . "<br />\n";
}


function roundToNearestInterval($timestamp)
{
    $timestamp += 60 * 30;
    list($m, $d, $y, $h, $i, $s) = explode(' ', date('m d Y H i s', $timestamp));
    if ($s != 0) $s = 0;

    if ($i < 15) {
        $i = 15;
    } else if ($i < 30) {
        $i = 30;
    } else if ($i < 45) {
        $i = 45;
    } else if ($i < 60) {
        $i = 0;
        $h++;
    }

    return mktime($h, $i, $s, $m, $d, $y);
}

收率:

03-01-2012 00:07 becomes 03-01-2012 00:45:00
03-01-2012 04:21 becomes 03-01-2012 05:00:00
03-01-2012 20:00 becomes 03-01-2012 20:45:00
03-01-2012 20:10 becomes 03-01-2012 20:45:00
03-01-2012 20:16 becomes 03-01-2012 21:00:00
03-01-2012 20:35 becomes 03-01-2012 21:15:00
03-01-2012 23:15 becomes 03-02-2012 00:00:00

答案 1 :(得分:2)

这样的事情:转换为unix时间戳,添加30 * 60,然后除以15 * 60,应用ceil(),然后乘以15 * 60,然后转换回日期。

答案 2 :(得分:2)

您可能需要对此进行更新,并测试时间接近最佳时间的几种情况。

<?php

$now = strtotime('now');
$timePlus30 = date('H:i', strtotime('+30 minutes', $now));

$minNow = date('i', strtotime($timePlus30));
$roundedMins = $minNow + ($minNow % 15);

$return = date('H', strtotime($timePlus30)) . ':' . ($roundedMins - 1);

?>

答案 3 :(得分:0)

不是最优雅的解决方案,但它应该有效(未经测试)

$hoursAndMins = explode(":",timeString); // should be "HH:MM"
$hours = $hoursAndMins[0]+(($hoursAndMins[1]+30)/60);
$mins = ($hoursAndMins[1]+30)%60;

if ($mins > 52){
   $mins = "00";
   $hours += 1;

}else if ($mins > 38){
    $mins = "45";
}else if ($mins > 23){
    $mins = "30";
}else if( $mins > 7){
    $mins = "15";
}else{
    $mins = "00";
}
echo $hours+ ":"+$mins;

[编辑]我认为另一个解决方案要好得多,但这个更详细