简体   繁体   English

CarbonPeriod 不会返回不完整的天数

[英]CarbonPeriod is not returning incomplete days

I want to split into days:我想分成几天:

2021-03-23T00:00:00Z
2021-03-24T23:00:00Z

Which represent 1 day and 1 hour.代表1天1小时。

If I try to make a carbon period with those:如果我尝试用这些来制作碳周期:

$periods = CarbonPeriod::create($start, "1 day", $end);

It will return:它将返回:

[0] = 2021-03-23T00:00:00Z
[1] = 2021-03-24T00:00:00Z

And I will lose 1 hour.我将失去 1 小时。

How should I do to make it return:我该怎么做才能让它返回:

[0] = 2021-03-23T00:00:00Z
[1] = 2021-03-24T00:00:00Z
[2] = 2021-03-24T00:23:00Z

Or if it is not possible, at least:或者,如果不可能,至少:

[0] = 2021-03-23T00:00:00Z
[1] = 2021-03-24T00:00:00Z
[2] = 2021-03-25T00:00:00Z

I believe that's how it's intended to work.我相信这就是它的工作方式。 If you want to include that last date that doesn't amount to a full period, you'll have to add it on your own.如果您想包含不等于完整期间的最后日期,则必须自行添加。

Including '2021-03-24T23:00:00Z' at the end.包括末尾的“2021-03-24T23:00:00Z”。

$start = '2021-03-23T00:00:00Z';
$end = '2021-03-24T23:00:00Z';

$period = (new Carbon($start))->toPeriod($end); // default period is +1d

$periodArray = $period->toArray();
if (!last($periodArray)->is($end)) {
    $periodArray[] = new Carbon($end);
}

Last lines can be converted into a single statement with tap()最后几行可以使用tap()转换为单个语句

$periodArray = tap($period->toArray(), function(&$array) use ($end) {
    if (!last($array)->is($end)) {
        $array[] = new Carbon($end);
    }
});

Including '2021-03-25T00:00:00Z' at the end包括末尾的“2021-03-25T00:00:00Z”

$start = '2021-03-23T00:00:00Z';
$end = '2021-03-24T23:00:00Z';

$period = (new Carbon($start))->toPeriod(
    (new Carbon($end))->startOfDay()->is($end)
        ? $end
        : (new Carbon($end))->addDays(1)
);

$periodArray = $period->toArray();

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

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