briannesbitt / Carbon

A simple PHP API extension for DateTime.
https://carbon.nesbot.com/
MIT License
16.57k stars 1.28k forks source link

diffFiltered with half hours #1500

Closed baptistebisson closed 5 years ago

baptistebisson commented 5 years ago

Hello,

I'm still having problems to get proper duration with two dates. Here is my example :

CarbonInterval::setCascadeFactors(array(
    'days' => array(8, 'hours'),
    'weeks' => array(5, 'days'),
));

$from = '2018-11-12 08:30:00';
$to = '2018-11-12 14:30:00';

$fromParsed = Carbon::parse($from);
$toParsed = Carbon::parse($to);

$resolution = CarbonInterval::hours();

$hours = $fromParsed->diffFiltered($resolution, function ($date) {
    return $date->isWeekday()
        && $date->hour >= 8
        && $date->hour !== 13
        && $date->hour < 18;
}, $toParsed);

$interval = CarbonInterval::hours($hours)->cascade();
return $interval->forHumans();

Working hours are from 08:30 to 12:30 and 14:00 to 18:00 so 8 hours in total. The problem is that there is no half hours interval like CarbonInterval::hours();.

In this example I want to get 4 hours 30 minutes but I need to do a lot of condition afterwards to test if this is half hours. Sometimes I remove one hour and add 30 minutes in $interval, or just add 30 minutes. For some case it's working but it's far too laborious.

I can't use $resolution = CarbonInterval::minutes(); because it's really slow when I have a duration of 1 week.

Is there any simpler solution for that ? Maybe a custom CarbonInterval ?

Thanks !

kylekatarnls commented 5 years ago

Hi,

The problem is that there is no half hours interval like CarbonInterval::hours();

You can use any interval:

CarbonInterval::minutes(30)

Or even: CarbonInterval::hour()->minutes(32)->seconds(30)

baptistebisson commented 5 years ago

Oh great, didn't know we could do that ! Thanks !