php add 15 minutes time interval to current time loop it till midnight

I need to add 15 minutes to the current time till the day's midnight.which should shows in the below format

11:15am
11:30am
11:45am

And it 'ld not be,

11:25am
11:40am
11:55am

My code is

$start =strtotime(date("d-m-Y h:i:s"));//strtotime('6:00am');
//echo $start;
//$end =strtotime('midnight');
$end = strtotime('12:00');//
$range = array();
while ($start <= $end)
{
echo date('h:ia',$start )."</br>";
$start = strtotime('+15 minutes',$start);
}

The above code results ,

11:28am
11:43am
11:58am

Question 1:

How to give end time as today midnight?

When I try strtotime('midnight'), it returns empty data.

Question 2:

How to display rounded time to nearest quarter?

2 answers

  • answered 2018-04-17 05:53 Syscall

    You can use 24:00 or 'tomorrow midnight' to get the next midnight. Your code use 12:00 which is "this noon".

    $min = round(date("i") / 15) * 15;
    $start = strtotime(date("Y-m-d H:$min:00"));
    $end = strtotime('24:00');
    $range = array();
    while ($start <= $end)
    {
        echo date('h:ia',$start )."</br>";
        $start = strtotime('+15 minutes',$start);
    }
    

    Will outputs:

    08:15am
    08:30am
    ...
    11:30pm
    11:45pm
    12:00am
    

    If you don't want to include "12:00am", you could change <= to <:

    while ($start < $end)
    

  • answered 2018-04-17 05:53 Justinas

    Problem is that your code must be started exactly 11:00 to get after 15 mins to be 11:15.

    You can create start time as 11:00:00 to properly set time (demo):

    $start =strtotime(date("h:00"));
    $end = strtotime('12:00');
    $range = array();
    
    while ($start <= $end)
    {
        $range[] = date('h:ia',$start );
        $start = strtotime('+15 minutes',$start);
    }
    
    var_dump($range);