Search code examples
phpdatetimeperiod

PHP DatePeriod before and after midnight with time only without date


I need to find 15 minute intervals between two times without date it all works fine if both times are before 00:00. I am passing times like: 17:00, 23:00 and 01:30.

After midnight is the problem of course it is another day so this is the reason it fails. I wanted know if there was a way to find the intervals regardless because the end time could be any eg. before or after midnight so adding in a real date may not be ideal, it will only be few hours after midnight nothing more than that.

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

Fiddle

Returns nothing, any help would be much appreciated.


Solution

  • If the end-time is shorter than the start-time, I don't see any option other than adding 1 day to the end-time.

    $start = "17:00";
    $end = "01:30";
    
    $dtStart = date_create('today '.$start);
    $dtEnd = date_create('today '.$end);
    if($dtEnd < $dtStart){
     $dtEnd->modify('+1 day');
    }
    
    $period = new DatePeriod(
        $dtStart,
        new DateInterval('PT15M'),
        $dtEnd
        );