PHP Carbon日期差异仅工作日

Bap*_*ste 5 php php-carbon

我正在尝试以人工格式获取两个日期之间的差异,但仅以工作日为单位。这是我的实际代码:

$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
Run Code Online (Sandbox Code Playgroud)

diffForHumans 非常适合我的需求,但是我找不到像 diffInDaysFiltered

我想达到的结果是:24 days 7 hours因为我们只有24工作日

preg_replace第一次尝试用$weekDay结果替换3天,但是如果我们有一个月的时间不正确,我就会:1 month 24 days 7 hours

我的问题有什么解决办法吗?

Bap*_*ste 9

这是感谢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
Run Code Online (Sandbox Code Playgroud)

这是部分:

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
    ]);
});
Run Code Online (Sandbox Code Playgroud)

然后只需在&& !$date->isHoliday()里面添加diffFiltered