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
248 views
in Technique[技术] by (71.8m points)

php - loop over the time till it reaches end time with specific interval

I'm trying to get all the time slots in a day with specified time interval (time interval is 2 hours i'e 120 minutes) like this

<?php

$start=strtotime('08:00');
$end=strtotime('18:00');

for ($i=$start + $k; $i<=$end - 1; $i = $i + 120*60) {
    echo date('g:i A',$i) . " - " . date('g:i A',$i  + 120*60 ) . '<br>';
}

?>

The above code outputs

8:00 AM - 10:00 AM
10:00 AM - 12:00 PM
12:00 PM - 2:00 PM
2:00 PM - 4:00 PM
4:00 PM - 6:00 PM

I'm trying to get the output something like below

8:00 AM - 10:00 AM
9:00 AM - 11:00 PM
10:00 AM - 12:00 PM
11:00 AM - 01:00 PM
12:00 PM - 02:00 PM
01:00 PM - 03:00 PM
02:00 PM - 04:00 PM
03:00 PM - 05:00 PM
04:00 PM - 06:00 PM

The time should not exceed 6 PM, I'm pretty new to PHP, can someone please help me on this, thanks

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Try using a while loop, as it makes for easier readble code.

$start = strtotime('08:00');
$end   = strtotime('18:00');

while ($start <= $end) {

    // Set dates to display
    $date1 = $start;        
    $date2 = $start + (120*60);

    echo date('g:i A',$date1) . " - " . date('g:i A',$date2) . '<br>';

    // Increment Start date
    $start += (60*60);

}


// 8:00 AM - 10:00 AM
// 9:00 AM - 11:00 AM
// 10:00 AM - 12:00 PM
// 11:00 AM - 1:00 PM
// 12:00 PM - 2:00 PM
// 1:00 PM - 3:00 PM
// 2:00 PM - 4:00 PM
// 3:00 PM - 5:00 PM
// 4:00 PM - 6:00 PM
// 5:00 PM - 7:00 PM
// 6:00 PM - 8:00 PM

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

...