将分钟添加到时间列表中


Adding minutes to a list of times

我在如何构建以给定倍数递增的时间方面遇到了问题。我想有一个函数,将采取3个参数,(开始,结束,偏移),这将给我一个输出:

以下函数的开始时间为0900,停止时间为1200,增量为30分钟的倍数。

有人能让我朝正确的方向出发吗?我本想用mktime做这个,但我没能让它发挥作用。

myfunction(9, 12, 30)

输出:

9:00 am
9:30 am
10:00 am
10:30 am
11:00 am
11:30 am
12:00 am

函数:

function myfunction($start, $end, $step){
    $start *= 3600; // 3600 seconds per hour
    $end   *= 3600;
    $step  *= 60;   // 60 seconds per minute
    for($i = $start; $i <= $end; $i += $step)
        echo date('h:i a', $i), '<br />';   
}

输出:

09:00 am
09:30 am
10:00 am
10:30 am
11:00 am
11:30 am
12:00 pm // You put am here in desired output
         // ,but I think you really wanted pm

编码板

strtotime是在PHP中处理日期和时间的另一个有用函数。

PHP手册的函数参考是一个很好的起点,当你想知道如何自己做事和利用内置函数时。从该页面中,如果你搜索"时间",你会发现PHP内置的日期/时间扩展。您将看到在PHP中有许多函数可用于处理日期和时间。

我会使用时间来创建一个dateTime对象。您可以只使用时间部分来格式化输出,因此一天的部分是不相关的。然后,您可以使用标准函数来添加时间间隔(其中一些函数将在本问题中讨论)。只需循环时间加法,直到达到或超过结束时间。

这也将处理各种特殊情况,否则你必须自己处理,例如AM/PM转换和开始时间晚于结束时间(这将持续到第二天)。

<?php
    function intervals($start, $end, $interval)
    {       
        $start_date   = strtotime($start.':00:00');
        $end_date     = strtotime($end.'00:00');
        $current_date = $start_date;
        while($current_date <= $end_date)
        {
            echo $current_date;
            $current_date = strtotime('+ '.intval($interval).' minute', $current_date);
        }
    }
?>

我想像这样的东西,就是你想要的。。(未经测试)

这是我的想法

 function myfunction($start, $end, $min_increm) {
  //just get a datetime do not matter the date
  $date = new DateTime('2000-01-01');
  //move to start hour, add 9 hour
  $start_date = $date->add(new DateInterval(PT{$start}H));
  $end date_date = $date->add(new DateInterval(PT{$end}H));
  while($date <= $end_date)
      //increment minutes and print
      echo($date->add(new DateInterval(PT{$min_increm}M))->format("H:m"));

}