tags:

views:

112

answers:

3

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)

A: 

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.

Kevin
Fatal error: Allowed memory size of 25165824 bytes exhausted (tried to allocate 71 bytes).
deadlyhifi
Can you try setting php memory limit to 32M?
Kevin
I don't have access to that, but it appears to be working OK now. Thanks for your help everyone.
deadlyhifi
A: 

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.

Scott Saunders
Good thinking. That *should* never happen but stranger things have happened.
deadlyhifi
Right. Lot's of things that shouldn't happen happen pretty frequently. Also, you might want to check the result of your strtotime() calls. It will return false or -1 (depending on your PHP version) if the input isn't good, which could also screw up your loop.
Scott Saunders
A: 

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";
}
chris
That's interesting. I'm not 5.3 yet, but it's good to know.
deadlyhifi