Carbon 库有助于设置一周的开放/关闭天数,因此您可以:
https://github.com/kylekatarnls/business-time
你可以这样做:
BusinessTime::enable(Carbon::class, [
'monday'. => [],
'tuesday' => ['00:00-24:00'],
'wednesday' => ['00:00-24:00'],
'thursday' => ['00:00-24:00'],
'friday' => [],
'saturday' => ['00:00-24:00'],
'sunday' => ['00:00-24:00'],
]);
$date = Carbon::parse('2019-06-01');
echo $date->addOpenTime('4 days');
这会增加 4 天,跳过周五和周一。
您基本上可以通过逐天添加循环来获得相同的结果,但是间隔越大,它的速度就会越慢。要优化操作,您应该首先添加完整的周数:
$daysToAdd = 36;
$skippedDays = ['Monday', 'Friday'];
$daysPerWeek = 7 - count($skippedDays);
$completeWeeks = floor($daysToAdd / $daysPerWeek);
function skip(CarbonInterface $date, array $skippedDays): CarbonInterface {
$date = $date->copy(); // if not using CarbonImmutable
while (in_array($date->format('l'), $skippedDays)) {
$date = $date->addDay();
}
return $date;
}
$start = Carbon::now(); // Or whatever date
$end = $start->copy()->addWeeks($completeWeeks); // ->copy() not needed if you use CarbonImmutable
$end = skip($end, $skippedDays);
// For each remaining days
for ($i = $daysToAdd % $daysPerWeek; $i--; $i > 0) {
$end = skip($end->addDay(), $skippedDays);
}
这是针对您的特定情况的普通版本,但如果您认为有一天,您将不得不处理小时间隔/小时精度而不是天,或者会有特殊的日子(如节假日例外),那么您应该绝对使用cmixin/business-time(上面的链接)。