在循环中更改时间增量,在不能被60整除时延续到下一个小时

时间:2013-06-06 18:09:52

标签: php mysql loops for-loop

下面是FOR循环的代码,它会按如下方式呈现一个列表:

...etc...
8:45 am
8:50 am
8:55 am
9:00 am
9:05 am
9:10 am
...etc.

这是一个运行五分钟间隔的脚本,这个脚本目前没有问题,因为它可以被60整除。但是,我需要把它放到我可以按照我想要的时间间隔制作的地方,实例9分钟。我试过改变 for ($j >= 0; $j <= 55; $j+=5) for ($j >= 0; $j <= 59; $j+=9)需要输出:

...etc...
8:36 am
8:45 am 
8:54 am
9:03 am
9:12 am
9:21 am
...etc

我想继续下一个小时并继续上面......并注意第一个小时是如何开始的:00 ....以及下一个小时的开始时间:03,因为54加9是03用小时说话,这就是我想要做的...... 但是它在小于或等于59之前仅输出最后一个值并且退出:即

...etc...
8:36 am
8:45 am
8:54 am
---AND STOPS HERE---

以上就是如何回应。

以下是我的代码:

$day = date("n/j/y");

            $startTime = date(strtotime($day." $coursetee_open_time_slashed"));
            ///needs to be in "16:00" format
            $endTime = date(strtotime($day." $coursetee_close_time_slashed"));
            ///needs to be in "16:00" format

            $timeDiff = round(($endTime - $startTime)/60/60);

            $startHour = date("G", $startTime);
            $endHour = $startHour + $timeDiff; 

            for ($i=$startHour; $i <= $endHour; $i++)
                {
                    for ($j >= 0; $j <= 55; $j+=5)
                    {
                        $time_pre = $i.":".str_pad($j, 2, '0', STR_PAD_LEFT);
                        $time = ''.$time_pre .' '.$day.'';

                        /////////////////////////////

                        $time_formated_for_cosmetic = date("g:i a", strtotime("$time"));
                        $time_formated_for_mysql = date("Y-m-d H:i:s", strtotime("$time"));
                            if (isset($tee_times_from_mysql[$time])) {
                                $time = '';
                            } else {
                                $time = '<option value="' . $time_formated_for_mysql . '">'.$time_formated_for_cosmetic .'</option>';
                            }
                            echo $time;
                    }

            }

2 个答案:

答案 0 :(得分:2)

$increment = 9;
$j = 0;
for ($i=$startHour; $i <= $endHour; $i++)
{
    for (; $j < 60; $j += $increment) // $j initialized outside of loop
    {
         // ...
    }
    $j -= 60; // Get start minute for next hour
}

答案 1 :(得分:1)

您可以在for循环中使用timestamp:

$day = date("n/j/y");

$coursetee_open_time_slashed = "16:00";
$coursetee_close_time_slashed = "18:00";


$startTime = strtotime($day." $coursetee_open_time_slashed"); // timestamp
// needs to be in "16:00" format
$endTime = strtotime($day." $coursetee_close_time_slashed"); // timestamp
// needs to be in "16:00" format

for ($time = $startTime; $time < $endTime; $time += 60 * 5) {
    echo date("Y-m-d H:i:s", $time) . "\n";
}