Calculate the number of days in overlapping or non-overlapping date ranges: PHP and Carbon implementation method
P粉754477325
P粉754477325 2023-09-09 14:50:29
0
1
561

How to get the number of days for 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 shown above, I have 3 date ranges. I need to get the total number of non-overlapping days in all 3 date ranges. In this example it would be 20 days. Is there any built-in method in Carbon/CarbonPeriod to achieve this?

P粉754477325
P粉754477325

reply all(1)
P粉475126941

You can just merge and deduplicate 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个日期,只包含没有重复的日期。
$uniqueDays = array_unique(array_merge($dateRange_1->toArray(), $dateRange_2->toArray(), $dateRange_3->toArray()));
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template