我正在尝试以人工格式来获取两个日期之间的差异,但仅以工作日为单位。这是我的实际代码:
$start = '2018-09-13 09:30:00';
$end = '2018-10-16 16:30:00';
$from = Carbon::parse($start);
$to = Carbon::parse($end);
$weekDay = $from->diffInWeekdays($to);
$human = $to->diffForHumans($from, true, false, 6);
var_dump($weekDay); //24
var_dump($human); // 1 month 3 days 7 hours
diffForHumans
非常适合我的需求,但是我找不到像diffInDaysFiltered
我想实现的结果是:24 days 7 hours
,因为我们只有24
个工作日
我首先尝试用preg_replace
将3天替换为$weekDay
的结果,但是如果我们有一个月的时间不正确,那么我会得到:1 month 24 days 7 hours
我的问题有解决方案吗?
答案 0 :(得分:1)
在此感谢imbrish
我需要使用级联因子来定义:
然后用diffFiltered
我只能选择工作日和工作时间。借助macro
CarbonInterval::setCascadeFactors(array(
'days' => array(10, 'hours'),
'weeks' => array(5, 'days'),
'months' => array(20, 'days'),
));
$resolution = CarbonInterval::hour();
$start = Carbon::parse('2017-07-13 11:00');
$end = Carbon::parse('2017-07-17 18:00');
$hours = $start->diffFiltered($resolution, function ($date) {
return $date->isWeekday() && $date->hour >= 8 && $date->hour < 18;
}, $end);
$interval = CarbonInterval::hours($hours)->cascade();
echo $interval->forHumans(); // 2 days 7 hours
这是macro部分:
Carbon::macro('isHoliday', function ($self = null) {
// compatibility chunk
if (!isset($self) && isset($this)) {
$self = $this;
}
// Put your array of holidays here
return in_array($self->format('d/m'), [
'25/12', // Christmas
'01/01', // New Year
]);
});
然后只需在&& !$date->isHoliday()
内添加diffFiltered