Split a time range into pieces by other time ranges

arrays, datetime, php, time

Solution

As you specifically asked for "some insight" rather than a full working answer, I'd personally go with arrays populated with "minutes".

$shift = array(
    'start' => '15:30:00',
    'end' => '18:30:00',

    'original' => array(),
    'unavailable' => array(),
    'modified' => array()
);

You'd then do some jiggery pokery to convert `15:30:00` into 930 and `18:30:00` into 1110 (number of minutes) which will give you the difference between start and end times.

Use `range()` to quickly fill up the `original` array, load in your `unavailable` in a similar format and then use things like `array_intersect()` and `array_diff()` to work out which minutes from the original shift are unavailable.

From that, build up the `modified` array, and read directly from there to your output.

Problem

I have a complicated task that I have been beating my head against the wall now for a few days. I've tried about 4 different approaches, however each seems to stall and it is becoming extremely frustrating. I have a time range. For example, 14:30:00 until 18:30:00. Consider this time range somebody's work shift. During this time range, they state they cannot work from 15:30:00 until 16:30:00 and from 17:30:00 until 18:30:00. I need to modify the original shift's start and end times to remove the conflicting shifts. The original shift array looks like this: ``` $original_shift[0]['start'] = '14:30:00'; $original_shift[0]['end'] = '18:30:00'; ``` And the time ranges to be removed from the original shift look like this: ``` $subshift[0]['start'] = '15:30:00'; $subshift[0]['end'] = '16:30:00'; $subshift[1]['start'] = '17:30:00'; $subshift[1]['end'] = '18:30:00'; ``` Here is a visualization: So, I basically need my original shift to look like this when I'm done: ``` $original_shift[0]['start'] = '14:30:00'; $original_shift[0]['end'] = '15:30:00'; $original_shift[1]['start'] = '16:30:00'; $original_shift[1]['end'] = '17:30:00'; ``` Some complications that I also need to consider are: These time ranges may be any times (not constrained to the half hour as I have used in my example), however I will know with 100% certainty the the unavailable time ranges will always start and end on or in between the original shift's start and end times. Unavailable times may butt up and/or take the entire original shift's time up. I'm not looking for someone to "write my code" as much as I am looking for someone who has dealt with something like this in the past and may have some insight on how they accomplished it.

Original source