Print time in 15-minute increments between two times in the same day

Viewed 34250

I'm trying to make a loop that will output this:

08:00
08:15
08:30
08:45
09:00
09:15
09:30
09:45
...etc

I need it to go from 08:00 to 17:00.

Here's my code so far:

function echo_datelist ($i, $j, $day, $month, $year)
{
    $time = str_pad($i, 2, '0', STR_PAD_LEFT).':'.str_pad($j, 2, '0', STR_PAD_LEFT);            
    $date = strtotime("$month $day $year $time:00");
    $sql = mysql_query("select b.room_type, c.name from bookings as b, customers as c where b.the_date='$date' and b.id_customer=c.id");
    
    echo $time.'<br />';
}

for ($i = 8; $i <= 16; $i++)
{
    for ($j = 0; $j <= 45; $j+=15)
        echo_datelist($i, $j, $day, $month, $year);
    
    echo_datelist(17, 0, $day, $month, $year);
}

The problem is, it is outputting a 17:00 in between each hour, example:

08:00
08:15
08:30
08:45
17:00
09:00
09:15
09:30
09:45
17:00

p.s. I know I shouldn't be making iterated trips to the database, but I'll solve that problem after this one.

9 Answers

Setting up a DateTime object with explicit bounds and its interval makes this process very clean. Remember to set the end time just passed what you want because the DatePeriod is "exclusive" of the end datetime.

Code: (Demo)

$period = new DatePeriod(
     new DateTime('08:00:00'),
     new DateInterval('PT15M'),
     new DateTime('17:00:01')
);

foreach ($period as $dt) {
    echo $dt->format("H:i") . "\n";
}

Output:

08:00
08:15
08:30
08:45
09:00
09:15
09:30
09:45
10:00
10:15
10:30
10:45
11:00
11:15
11:30
11:45
12:00
12:15
12:30
12:45
13:00
13:15
13:30
13:45
14:00
14:15
14:30
14:45
15:00
15:15
15:30
15:45
16:00
16:15
16:30
16:45
17:00
Related