Search code examples
laraveldatetime-formatlaravel-7php-carbon

Laravel 7: How to add numeric value with date?


I'm calculating the difference between two dates. I want to make addition/subtraction a numeric/decimal value with the date.

Example: 

Start = 2022-06-28 
end = 2022-06-29 


total= (start - 0.5) - ( end - 0)
     = 1.5
or 
total= (start - 0) - ( end - 0)
     = 2
or 
total= (start - 0.5) - ( end - 0.5)
     = 1

Code:

$second_half = $request->session_1; // value = 0.5
$first_half = $request->session_2; // value = 0.5
$start = Carbon::parse($request->start_date); // value (YYYY-MM-DD) = 2022-06-28
$end = Carbon::parse($request->end_date); // value (YYYY-MM-DD) = 2022-06-29
$total_days = $end->diff($start); // this result can be decimal like 1.5

Actually, I want to divide the full day into two-part. First half and second half. So when I calculating the difference between two dates it should calculate the full day by (first half + second half). If I select 2022-06-28 first half and 2022-06-29 second half, it will count 2 days. If I select 2022-06-28 first half and 2022-06-29 first half, it will count 1.5 days.

I hope my concept is clear to you. How can I make this calculation?


Solution

  • Can you test please the followind code?

        $startDate = '2022-06-28';
        $endDate = '2022-06-29';
        $second_half = 0.5;
        $first_half = 0.5;
    
        $start = \Carbon\Carbon::parse($startDate);
        $end = \Carbon\Carbon::parse($endDate);
        $total_days = (float) $end->diff($start)->days;
    
        if($first_half) {
            $total_days += $first_half;
        }
        if ($second_half) {
            $total_days += $second_half;
        }
        
        $total_days = preg_replace('/\\.$/','.0',rtrim($total_days,'0'));
        
    // dd($total_days);