skip to Main Content

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

Answers


  1. You can achive that using ->setMonth:

    $monthNumber = 1;
    $this->dateRange = CarbonPeriod::create(now()->startOfMonth()->setMonth($monthNumber), now()->endOfMonth())->toArray();
    
    Login or Signup to reply.
  2. 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());
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search