简体   繁体   English

CarbonPeriod 2月通行证

[英]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.我希望它是 2 月 28 日而不是 3 月 1 日。 29 january 28february and 29 march 1 月 29 日 2 月 28 日和 3 月 29 日

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.这是正常行为,您会得到与DatePeriod相同的情况,如果日期高于一个月中的天数,它会溢出,但您仍然可以轻松检测到当前日期与初始日期的溢出。

But you should more likely do a simple for-loop for this, it's way less overkill:但是你应该更可能为此做一个简单的for循环,这样就不会那么矫枉过正了:

$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");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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