问题描述
如何在几分钟内获得两个日期之间的差异,但不包括周末(周六和周日)
<?PHP
require_once __DIR__ . '/autoload.PHP';
use Carbon\Carbon;
use Carbon\CarbonInterval;
$created = Carbon::parse("2021-04-11 00:07:13");
$firstResponse = Carbon::parse("2021-04-12 12:35:04");
$diffInMinutes = $created->diffFiltered(CarbonInterval::minute(),function($date){
return !$date->isWeekend();
},$firstResponse);
echo $diffInMinutes;
错误信息是 Carbon error: Could not find next valid date
谁能帮帮我?谢谢。
解决方法
这实际上发生在达到最大循环数 (NEXT_MAX_ATTEMPTS = 1000
) 时,由于周末的分钟数,这里会发生这种情况。
虽然您的方法在理论上是正确的,但它会减慢并在多天的间隔内每分钟迭代一次。
您宁愿按天计算,直到一天结束,如果不是周末,则添加 diffInMinutes,然后在第二天再次计算。
use Carbon\CarbonImmutable;
$created = CarbonImmutable::parse("2021-04-11 00:07:13");
$firstResponse = CarbonImmutable::parse("2021-04-12 12:35:04");
$diffInMinutes = 0;
$step = $created;
while ($step < $firstResponse) {
if ($step->isWeekend()) {
$step = $step->next('Monday');
continue;
}
$nextStep = min($firstResponse,$step->addDay()->startOfDay());
$diffInMinutes += $step->diffInMinutes($nextStep);
$step = $nextStep;
}
echo $diffInMinutes;
注意:警告,如果使用 Carbon
而不是 CarbonImmutable
,您需要将 $step = $created;
替换为 $step = $created->toImmutable();