I have two datetime intervals, and I want to identify the overlapping period between them. For instance, if I have intervals:
- 01-12-2023 01:00:00 to 12-12-2023 15:00:00
- 10-12-2023 11:00:00 to 24-12-2023 16:00:00
I need to retrieve the common interval, which in this case is 10-12-2023 11:00:00 to 12-12-2023 15:00:00. How can I achieve this in PHP, either using native functions or a library like Carbon?
Here is my code :
<?php
require 'vendor/autoload.php';
use Carbon\Carbon;
$range1Start = Carbon::parse('2023-12-01 01:00:00');
$range1End = Carbon::parse('2023-12-12 15:00:00');
$range2Start = Carbon::parse('2023-12-10 11:00:00');
$range2End = Carbon::parse('2023-12-24 16:00:00');
if ($range1Start->lessThan($range2End) && $range2Start->lessThan($range1End)) {
// Calculate the overlapping period
$overlapStart = $range1Start->max($range2Start);
$overlapEnd = $range1End->min($range2End);
echo "Overlap: {$overlapStart->toDateTimeString()} to {$overlapEnd->toDateTimeString()}\n";
} else {
echo "No overlap.\n";
}
There is a simple algorithm you can follow:
Here is an example of implementation: