Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...