dony113407
2010-03-23 14:02
浏览 72
已采纳

开始和结束时间,分为1小时段

I have a start and end time in a timestamp format. I want to split these into timeslots of e.g 1 hour.

$t1 = strtotime('2010-05-06 12:00:00');
$t2 = strtotime('2010-05-06 18:00:00');

$timeslots = array();

while ($t1 < $t2) {
$t1 = $t1 + 3600;
$timeslots[] = $t1;
}

foreach ( $timeslots as $slot ) {
echo date("Y-m-d H:i:s", $slot) . '<br/>';
}

Is this the most efficient way to do it or is there a better, more versatile way to do this?

Occasionally when trying it with other numbers for different length timeslots there was a Fatal error: Allowed memory size exhausted which makes me think it's not very efficient. Though that doesn't appear to be happening now...

(I'm building a booking sytem)

图片转代码服务由CSDN问答提供 功能建议

我有 timestamp 格式的开始和结束时间。 我想将它们分成1小时的时间段。

  $ t1 = strtotime('2010-05-06 12:00:00'); 
 $ t2 =  strtotime('2010-05-06 18:00:00'); 
 
 $ timeslots = array(); 
 
而($ t1&lt; $ t2){
 $ t1 = $ t1 + 3600;  
 $ timeslots [] = $ t1; 
} 
 
foreach($ timeslots as $ slot){
echo date(“Ymd H:i:s”,$ slot)。  '&lt; br /&gt;'; 
} 
   
 
 

这是最有效的方法,还是有更好,更通用的方法来做到这一点 ?

偶尔尝试使用不同长度时间段的其他数字时会出现致命错误:允许的内存大小耗尽,这让我认为它不是很有效。 虽然现在似乎没有发生......

(我正在建立预订系统)

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • douba2011 2010-03-23 14:06
    已采纳

    Have you tried

    while ($t1 < $t2) {
       $t1 = strtotime('+1 hour', $t1);
       $timeslots[] = date('Y-m-d H:i:s', $t1);
    }
    
    foreach ( $timeslots as $slot ) {
       echo $slot . '<br/>';
    }
    

    Somewhat the same but cleaner. And as was said strtotime will handle date changes like leap years. What is your PHP memory limit set at? Might be too low.

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongsuiying7773 2010-03-23 14:13

    Rather than

    $t1 = $t1 + 3600;
    

    You'll be better off with

    $t1 = strtotime('+1 hour', $t1);
    

    The latter will adjust to daylight savings time, leap years, etc.

    Otherwise, your code looks fine. If you ran out of memory it was probably due to an infinite loop. You probably want to add code to make sure that $t2 is larger than $t1, and to switch them if they aren't.

    评论
    解决 无用
    打赏 举报
  • doumou1864 2010-03-23 16:44

    using php 5.3

    $dateTimes = new DatePeriod(
        new DateTime($start),
        new DateInterval('PT1H'),
        new DateTime($end)
    );
    
    foreach ($dateTimes as $dt) {
        echo $dt->format('Y-m-d H:i:s'), "
    ";
    }
    
    评论
    解决 无用
    打赏 举报