I'm trying to get a list of previous months using Carbon
.
Expected result:
January, February, March, April
What I did so far:
$now = Carbon::now();
$startMonth = $now->startOfMonth()->subMonth($now->month);
$currentMonth = $now->startOfMonth();
$diff = $currentMonth->diffInMonths($startMonth);
I've used Carbon::now()
to get the first month of the year, then I tried to calculate the difference between the dates but I got 0
.
Also I canno find any method that returns a list of months as the expected output.
CodePudding user response:
You're setting the original variable to December 1st of the previous year, since you keep modifying the original instead of copying it. Instead, create two variables off of now()
, then you can use that to create a CarbonPeriod to iterate through.
$firstOfYear = Carbon::now()->firstOfYear();
$firstOfLastMonth = Carbon::now()->firstOfMonth()->subMonth(); // If you want to include the current month, drop ->subMonth()
$period = CarbonPeriod::create($firstOfYear, '1 month', $firstOfLastMonth);
foreach($period as $p) echo $p->format('F')."\n";
CodePudding user response:
Why not a simple while
loop?
use Carbon\Carbon;
$previousMonths = [];
$currentDate = Carbon::now()->startOfMonth();
while ($currentDate->year == Carbon::now()->year) {
$previousMonths[] = $currentDate->format('F');
$currentDate->subMonth();
}
$previousMonths
would now be:
[
"April",
"March",
"February",
"January",
]
Edit
If you need them in the opposite order, then:
$previousMonths = array_reverse($previousMonths);
Then $previousMonths
will be:
[
"January",
"February",
"March",
"April",
]
CodePudding user response:
Another approach using PHP range:
$now = Carbon::now();
$months = collect( range(1, $now->month) )->map( function($month) use ($now) {
return Carbon::createFromDate($now->year, $month)->format('F');
})->toArray();
This should return a collection of months (array if toArray() is used) from January until the current month (similar to the expected result)