简体   繁体   中英

CarbonPeriod pass february

$start_day = $installment->'2021-01-29';
$end = Carbon::createFromFormat('Y-m-d', $start_day)->addMonth(24);
$period =  CarbonPeriod::create($start_day, '1month', $end);

$years = [];
foreach ($period as $date) {

    $years[$date->format("Y")][$date->format("m")]['title'] = $date->format("d ") .$date->format("n"));
    
}

result

"29 January"
"01 March"

It pass february. I wanna it to be 28 february istead of 1 march. 29 january 28february and 29 march

This is the normal behavior, you would get the same with DatePeriod , it overflows if the day is higher than the number of days in a month, still you can easily detect this overflow comparing current day to your initial one.

But you should more likely do a simple for-loop for this, it's way less overkill:

$start_day = '2021-01-29';
$start = CarbonImmutable::parse($start_day);

$years = [];
for ($i = 0; $i < 24; $i++) {
    $date = $start->addMonthsNoOverflow($i);

    $years[$date->format("Y")][$date->format("m")]['title'] = $date->format("d n");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM