Start and end time, split into 1 hour segments

让人想犯罪 __ 提交于 2019-12-18 09:13:17

问题


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)


回答1:


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.




回答2:


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.




回答3:


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'), "\n";
}


来源:https://stackoverflow.com/questions/2500482/start-and-end-time-split-into-1-hour-segments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!