1

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.

Abu Nooh
  • 846
  • 4
  • 12
  • 42

2 Answers2

1

Because you're using only the time portion, the day will be automatically set to the current day.. which makes the end being smaller than the begin.

But if you take real dates (which ones doesn't really matter) and pick the next day at 1'clock...

$period = new DatePeriod(
    new DateTime("1970-01-01 17:00"),
    new DateInterval('PT15M'),
    new DateTime("1970-01-02 01:00")
    );
    
foreach ($period as $date) {
    echo $date->format("H:i").' - ';
}

hth

Honk der Hase
  • 2,459
  • 1
  • 14
  • 26
  • Yes it does help, although it exposes a flaw in my question. I've updated to reflect it. The end time is dynamic so it could be before or after midnight in this case the date would need to change. I take it without the date I don't have much option? – Abu Nooh Sep 06 '20 at 16:16
  • Use real dates and you have problem... or you'd have to make the assumption: if start greater end, then the end-time is on the next day – Honk der Hase Sep 06 '20 at 20:47
1

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
    );
jspit
  • 7,276
  • 1
  • 9
  • 17