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粉4751269412023-09-10 10:41:19
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()));