Skip to content
Advertisement

Find out by how many days two date ranges overlap in PHP

I have two arbitrary date ranges, for example:

JavaScript

How do I find out in PHP, by how many days these date ranges overlap? (In the example above it’s 5 days)

Advertisement

Answer

Here’s a solution using DateTime and DateInterval objects:

JavaScript

Output

JavaScript

Demo on 3v4l.org

Update

Here is a more robust version of the code that allows for arbitrary overlapping of the ranges (including one being contained entirely in the other):

JavaScript

It can be called like this:

JavaScript

Demo on 3v4l.org

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