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

67 Views Asked by At

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.

2

There are 2 best solutions below

2
Lucas Pace On BEST ANSWER

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);
0
KyleK On

I don't see why to use now() in this case. Create new objects from scratch, and if you want those months on the current year, pass null as first parameter to create():

$startMonth = 1;
$endMonth = 3;
$start = Carbon::create(null, $startMonth);
$end = Carbon::create(null, $endMonth)->endOfMonth();
dd(CarbonPeriod::create($start, $end)->toArray());

And just use parse() to work with month name instead of number:

$startMonth = 'January';
$endMonth = 'March';
$start = Carbon::parse($startMonth);
$end = Carbon::parse($endMonth)->endOfMonth();
dd(CarbonPeriod::create($start, $end)->toArray());