5

I have two intervals of times , let's say

  • Interval X: [01-11-2019 08:00, 01-11-2019 14:00]
  • Interval Y: [01-11-2019 12:00, 01-11-2019 17:00]

I need to get the intersect between these intervals so the answer should be 2 hours because the interval Y intersect with interval X in 2 hours only, so how to do that in Carbon ? Is there any library or function to do that ? I've searched but no useful results. Thanks

Please note i mean difference between two intervals not just startDate and endDate

Mohamed Gamal
  • 145
  • 1
  • 2
  • 12
  • Does this answer your question? [Carbon Difference in Time between two Dates in hh:mm:ss format](https://stackoverflow.com/questions/33575239/carbon-difference-in-time-between-two-dates-in-hhmmss-format) – Shiva Nov 07 '19 at 13:58
  • no there is a diff between two normal dates . What i need the diff between intervals – Mohamed Gamal Nov 07 '19 at 13:59

2 Answers2

6

An interval represents an amount of time passed from timeA to timeB regardless of a start time or an end time. I guess you mean a period (date range).

You can calculate the overlap (intersection) between two date ranges using CarbonPeriod class and simple function.

I would like to suggest the following implementation:

<?php
use Carbon\CarbonInterval;
use Carbon\CarbonPeriod;

function calculatePeriodsOverlap(CarbonPeriod $periodA, CarbonPeriod $periodB): CarbonInterval
{
    if (!$periodA->overlaps($periodB)) {
        return new CarbonInterval(0);
    }

    $firstEndDate = min($periodA->calculateEnd(), $periodB->calculateEnd());
    $latestStartDate = max($periodA->getStartDate(), $periodB->getStartDate());

    return CarbonInterval::make($firstEndDate->diff($latestStartDate));
}


$periodX = new CarbonPeriod('01-11-2019 08:00', '01-11-2019 14:00');
$periodY = new CarbonPeriod('01-11-2019 12:00', '01-11-2019 17:00');

calculatePeriodsOverlap($periodX, $periodY)->forHumans(); // returns "2 hours"
2

You don't need a library like Carbon. Use simply DateTime.

$iX0 = date_create('01-11-2019 08:00');  //Start interval X
$iX1 = date_create('01-11-2019 14:00');  //End interval X
$iY0 = date_create('01-11-2019 12:00');  //Start interval Y
$iY1 = date_create('01-11-2019 17:00');  //End interval Y

$i0 = max($iX0,$iY0);
$i1 = min($iX1,$iY1);
if($i1 >= $i0){
  $diff = $i0->diff($i1);
  echo $diff->h." Hours";  //full Hours
}
else {
  echo 'no itersect';
}

Output:

2 Hours

Note: This example only calculates full hours without minutes and seconds.

Try it yourself: https://3v4l.org/uS1Fh

Yevgeniy Afanasyev
  • 37,872
  • 26
  • 173
  • 191
jspit
  • 7,276
  • 1
  • 9
  • 17