search

Home  >  Q&A  >  body text

Calculate the number of days in overlapping or non-overlapping date ranges: PHP and Carbon implementation method

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粉754477325P粉754477325431 days ago542

reply all(1)I'll reply

  • P粉475126941

    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()));
    

    reply
    0
  • Cancelreply