Home > Software design >  Laravel 7: How to add numeric value with date?
Laravel 7: How to add numeric value with date?

Time:06-29

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?

CodePudding user response:

Can you test please the followind code?

    $second_half = 0.5;
    $first_half = 0.5;
    $start = \Carbon\Carbon::parse('2022-06-28');
    $end = \Carbon\Carbon::parse('2022-06-29');
    $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);

CodePudding user response:

$second_half = $request->session_1; // value = 0.5
$first_half = $request->session_2; // value = 0.5
$start = Carbon::parse($request->start_date . ($first_half ? ' 12:00' : ' 00:00'));
$end = $second_half
    ? Carbon::parse($request->end_date . ' 12:00')
    : Carbon::parse($request->end_date)->addDay();
$total_days = $end->floatDiffInDays($start);
  • Related