需要期间日期时间的第一天和最后一天

时间:2020-02-13 13:46:39

标签: php laravel datetime php-carbon

我正在与Carbon Period合作,以获取两个日期之间间隔为'N'天的时间。

在每个周期的迭代中,我需要知道如何获得每个周期的第一天和最后一天。

例如:

$period = CarbonPeriod::create('2019-10-01', '30 days', '2020-02-15');
// What I need is
// Period 1: from 2019-10-01 to 2019-10-31
// Period 2: from 2019-11-01 to 2019-11-30
// Period 3: from 2019-12-01 to 2019-12-31
// Period 4: from 2020-01-01 to 2020-01-31
// Period 5: from 2020-02-01 to 2020-02-15

2 个答案:

答案 0 :(得分:1)

我认为您无法获得每个期间的开始/结束日期,但是您可以使用副本/设置者来获得结束期间的第二天。

$period = CarbonPeriod::create('2019-10-01', '30 days', '2020-02-15');
$start = null;
foreach($period as $key=>$date) {
    if(!$start) {
        echo "Start 1 : ".$period->getStartDate()->toDateString(). " End : ".$date->toDateString()."\n";
        $start = $date->copy()->addDay();
    } else {
        echo "Start 2 : ".$start->toDateString(). " End : ".$date->toDateString()."\n";
    }
    $start = $date->copy()->addDay();
}
if($start->lt($period->getEndDate())) {
    echo "Start : ".$start->toDateString(). " End : ".$period->getEndDate()->toDateString()."\n";
}
//Start : 2019-10-01 End : 2019-10-01
//Start : 2019-10-02 End : 2019-10-31
//Start : 2019-11-01 End : 2019-11-30
//Start : 2019-12-01 End : 2019-12-30
//Start : 2019-12-31 End : 2020-01-29
//Start : 2020-01-30 End : 2020-02-15

由于2020-01-30-2020-02-15不是30天,因此不会将其创建为另一个间隔。如果需要,您必须像最后几行一样手动检查是否已添加。

答案 1 :(得分:1)

首先,您应该使用1 month作为间隔而不是30 days

$period = CarbonPeriod::create('2019-10-01', '1 month', '2020-02-15');

然后,您可以使用endOfMonth()方法来获得预期的结果:

$dates = [];

foreach ($period as $index => $date) {
    $dates[] = sprintf("Period %s: from %s to %s",
        $index + 1,
        $date->toDateString(),
        $period->getEndDate()->min($date->endOfMonth())->toDateString()
    );
}