Mohamed Gamal
Mohamed Gamal

Reputation: 145

How to get difference between two intervals of time in Carbon

I have two intervals of times , let's say

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

Upvotes: 5

Views: 4521

Answers (2)

jspit
jspit

Reputation: 7683

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

Upvotes: 2

Vladimir Ivanenko
Vladimir Ivanenko

Reputation: 196

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"

Upvotes: 8

Related Questions