How To Split Time Into Intervals With PHP

-

Recently, I needed to get every time - in thirty minute intervals - between a given start time and a given end time.

Luckily, PHP has a DatePeriod class and DateInterval class to handle that type of thing.

Here’s how it works

Solution

Explanation

DateTime

You’ve got your standard DateTime objects for the start and end time, nothing fancy.

DateInterval

For the DateInterval class there are period designators. Period designators allow you to define the interval you want to work with. In my case I needed the time range to be split into 30 minute intervals, so my period designator was PT30M.

Here is the full list of available designators.

P - period (always required)

Y - years

M - months

D - days

W - weeks. These get converted into days, so can not be combined with D.

H - hours

M - minutes

S - seconds

T - Time (if the duration contains time elements, that portion of the specification is preceded by the letter T)

Here are a few more interval examples:

Every 1-½ years - P1Y6M

Every hour - PT1H

Every 3 days - P3D

Hopefully you get the idea.

DatePeriod:

Next we’ve got a DatePeriod class, which accepts a start time, an interval, and an end time.

Sidebar

Initially, as the $end_time, I tried to use a modified version of $start_time.

$end_time = $start_time->modify(‘+1 day’);

However, DatePeriod didn’t like it. And the foreach wouldn’t return anything. Apparently you have to use two completely separate DateTime objects.

Back to the show

Once you create the DatePeriod you can loop through the results, and you’re good to go.

Great success!