Php 需要周期datetime上的第一天和最后一天
我用碳周期来计算两个日期之间的间隔时间 在每个周期的迭代中,我需要知道如何获得每个周期的第一天和最后一天 例如:Php 需要周期datetime上的第一天和最后一天,php,laravel,datetime,php-carbon,Php,Laravel,Datetime,Php Carbon,我用碳周期来计算两个日期之间的间隔时间 在每个周期的迭代中,我需要知道如何获得每个周期的第一天和最后一天 例如: 我不认为你可以得到每个周期的开始/结束日期,但是你可以使用一个拷贝/设置器来获得周期结束的第二天 $period = CarbonPeriod::create('2019-10-01', '30 days', '2020-02-15'); $start = null; foreach($period as $key=>$date) { if(!$start) {
我不认为你可以得到每个周期的开始/结束日期,但是你可以使用一个拷贝/设置器来获得周期结束的第二天
$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个月
作为间隔,而不是30天
:
$period=CarbonPeriod::create('2019-10-01','1个月','2020-02-15');
然后您可以使用endOfMonth()
方法获得预期结果:
$dates=[];
foreach($期间为$索引=>$日期){
$dates[]=sprintf(“期间%s:从%s到%s”,
$index+1,
$date->toDateString(),
$period->getEndDate()->min($date->endOfMonth())->toDateString()
);
}
在您查看文档后,如何做到这一点还不清楚?我当然读过文档。很明显,在开始日期和结束日期之间要有一个间隔,但不知道如何从开始日期和结束日期的每个间隔中获得第一天和最后一天。
$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