Search code examples
phplaraveleloquentphp-carbon

laravel how to use carbon Period to archive month complete date get


I'm trying to archive month date 1 to month end date with.

below code now get this year month complete date 1 to 31 by below code. but it only gives current year month I want to pass dynamic year month name or month number to archive date list

 $this->dateRange = CarbonPeriod::create(now()->startOfMonth(), now()->endOfMonth())->toArray();
 dd($this->dateRange);

Result I get:

 01-01-2024
 02-01-2024
    ...
 31-01-2024

I'm trying to archive month date 1 to month end date in array.


Solution

  • You can achive that using ->setMonth:

    $monthNumber = 1;
    $this->dateRange = CarbonPeriod::create(now()->startOfMonth()->setMonth($monthNumber), now()->endOfMonth())->toArray();
    

    }

    But if you want to work with different years (instead of only the now() year), I recommend a different approach:

    $year = 2024;  // Replace with the desired year
    $month = 5;    // Replace with the desired month number or month name 
    
    // Create a Carbon instance for the first day of the specified month
    $startDate = Carbon::create($year, $month, 1)->startOfMonth();
    
    // Create a Carbon instance for the last day of the specified month
    $endDate = $startDate->endOfMonth();
    $dateRange = CarbonPeriod::create($startDate, $endDate)->toArray();
    dd($dateRange);