PHP 碳日期差异仅与工作日
PHP Carbon date difference with only working days
我正在尝试以人工格式获取两个日期之间的差异,但仅限于工作日。这是我的实际代码:
$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
来用 $weekDay
结果替换 3 天,但是如果我们有一个月的时间,它就不正确了,我有:1 month 24 days 7 hours
我的问题有解决办法吗?
感谢imbrish
,这是答案
我需要使用级联因子来定义:
- 一天有多少小时
- 一周有多少天
- 一个月有多少天
然后用 diffFiltered
我只能 select 工作日和工作时间。由于 macro
,您还可以在 public 假期添加过滤器
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
]);
});
然后只需在 diffFiltered
中添加 && !$date->isHoliday()
我正在尝试以人工格式获取两个日期之间的差异,但仅限于工作日。这是我的实际代码:
$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
来用 $weekDay
结果替换 3 天,但是如果我们有一个月的时间,它就不正确了,我有:1 month 24 days 7 hours
我的问题有解决办法吗?
感谢imbrish
,这是答案我需要使用级联因子来定义:
- 一天有多少小时
- 一周有多少天
- 一个月有多少天
然后用 diffFiltered
我只能 select 工作日和工作时间。由于 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
]);
});
然后只需在 diffFiltered
&& !$date->isHoliday()