Start and end time, split into 1 hour segments

2019-01-28 14:28发布

问题:

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";
}


标签: php strtotime