Home > Net >  Get count of days in 2 or more overlapping(or not) date ranges in PHP, Carbon
Get count of days in 2 or more overlapping(or not) date ranges in PHP, Carbon

Time:09-02

How can I get amount of days in 2 or more potentially overlapping date ranges (CarbonPeriod)?

    $startDate_1 = '2022-12-01';
    $endDate_1 = '2022-12-10';

    $startDate_2 = '2022-12-06';
    $endDate_2 = '2022-12-15';

    $startDate_3 = '2022-12-21';
    $endDate_3 = '2022-12-25';

    $dateRange_1 = CarbonPeriod::create($startDate_1, $endDate_1);
    $dateRange_2 = CarbonPeriod::create($startDate_2, $endDate_2);
    $dateRange_3 = CarbonPeriod::create($startDate_3, $endDate_3);

For example, as above I have 3 dates ranges. I need to get total amount of days in all 3 dates ranges without overlapping. In this example it should be 20. Is there any build in method in Carbon/CarbonPeriod?

CodePudding user response:

You can just merge and unique them.

$startDate_1 = '2022-12-01';
$endDate_1 = '2022-12-10';

$startDate_2 = '2022-12-06';
$endDate_2 = '2022-12-15';

$startDate_3 = '2022-12-21';
$endDate_3 = '2022-12-25';

$dateRange_1 = CarbonPeriod::create($startDate_1, $endDate_1);
$dateRange_2 = CarbonPeriod::create($startDate_2, $endDate_2);
$dateRange_3 = CarbonPeriod::create($startDate_3, $endDate_3);

// 20 dates, only days that were not duplicated.
$uniqueDays = array_unique(array_merge($dateRange_1->toArray(), $dateRange_2->toArray(), $dateRange_3->toArray()));
  • Related