Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

php - Start and end time, split into 1 hour segments

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...