Home > Software design >  Split date range into months ranges in Laravel
Split date range into months ranges in Laravel

Time:02-24

For example I have a start and end date like this:

Input:

$startDate = 2022-01-03
$endDate = 2022-03-03

My desired output is:

[0] => Array
         (
             [start] => 2022-01-03
             [end] => 2022-01-31
         )

[1] => Array
         (
             [start] => 2022-02-01
             [end] => 2022-02-28
         )
[2] => Array
         (
             [start] => 2022-03-01
             [end] => 2022-03-03
         )

CodePudding user response:

This should work...

 $startDate = \Carbon\Carbon::parse('2022-01-03')->format('Y-m-d');
    $endDate = \Carbon\Carbon::parse('2022-03-03')->format('Y-m-d');
    $period = \Carbon\CarbonPeriod::create($startDate, '1 month', $endDate);
    

    $p = array();

    foreach ($period as $date) {

        $p[] = (object)[
          "start"=> ($date->firstOfMonth()->gt($startDate)) ? $date->firstOfMonth()->toDateString(): $startDate, 
          "end"=> ($date->lastOfMonth()->lt($endDate)) ? $date->lastOfMonth()->toDateString() : $endDate
          ];
          
    }

    print_r($p);
  • Related