我正在嘗試使用Carbon.
預期結果:
January, February, March, April
到目前為止我做了什么:
$now = Carbon::now();
$startMonth = $now->startOfMonth()->subMonth($now->month);
$currentMonth = $now->startOfMonth();
$diff = $currentMonth->diffInMonths($startMonth);
我曾經Carbon::now()得到一年中的第一個月,然后我試圖計算日期之間的差異,但我得到了0.
此外,我找不到任何回傳月份串列作為預期輸出的方法。
uj5u.com熱心網友回復:
您將原始變數設定為上一年的 12 月 1 日,因為您一直在修改原始變數而不是復制它。相反,從 中創建兩個變數now(),然后您可以使用它來創建 CarbonPeriod 進行迭代。
$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";
uj5u.com熱心網友回復:
為什么不是一個簡單的while回圈?
use Carbon\Carbon;
$previousMonths = [];
$currentDate = Carbon::now()->startOfMonth();
while ($currentDate->year == Carbon::now()->year) {
$previousMonths[] = $currentDate->format('F');
$currentDate->subMonth();
}
$previousMonths現在是:
[
"April",
"March",
"February",
"January",
]
編輯
如果您以相反的順序需要它們,那么:
$previousMonths = array_reverse($previousMonths);
然后$previousMonths將是:
[
"January",
"February",
"March",
"April",
]
uj5u.com熱心網友回復:
使用 PHP 范圍的另一種方法:
$now = Carbon::now();
$months = collect( range(1, $now->month) )->map( function($month) use ($now) {
return Carbon::createFromDate($now->year, $month)->format('F');
})->toArray();
這應該回傳從一月到當前月份的月份集合(如果使用 toArray() 則為陣列)(類似于預期結果)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/465654.html
上一篇:資料庫結構常量
下一篇:PHP-簡單表格
