Skip to content
Advertisement

How to get total time from several date ranges in php

I have several date ranges in form of DateTime $begin, DateTime $end. Those ranges can overlap in every possible way:

JavaScript

etc.

What I am trying to do is to get length (in seconds or DateInterval) of those ranges between start of the first one and the end of the latest one (fourth in the case above), excluding regions not covered by any range.

There is no problem for only two ranges, but I can’t work out how to extend it to handle more than two.

EDIT:

JavaScript

For two ranges only I have a function which returns DateInterval object:

JavaScript

where addIntervals is a function that returns sum of two DateInterval objects as another DateInterval object.

This is some basic version, in my production code I use a lot of other irrelevant stuff.

To simplify let’s say we have only Time part of DateTime: (’06:00:00′ to ’08:00:00′), (’07:00:00′ to ’09:00:00′), (’06:00:00′, ’08:00:00′), (’11:00:00′ to ’12:00:00′) (there will be many such ranges). The result I’d like to have now is 4 hours (from 6:00 to 9:00 + from 11:00 to 12:00).

Advertisement

Answer

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement