Search code examples
phplaravel-8php-carbon

can I calculate difference between 6 AM to 12 AM in hours using carbon in Laravel?


I'm having a problem with the Laravel project and I want to estimate the difference of 2-time in my project using the carbon package. The below code is what I used to calculate.

        $carbon_startDate = Carbon::parse($working_time['start_time'])->format('H:i:s');
        $carbon_edate = Carbon::parse($working_time['end_time'])->format('H:i:s');
        $totalDuration = Carbon::parse($carbon_startDate)->diffInHours($carbon_edate);

But here I am facing a new problem. I set the start time to 6 AM and the end time is 12 AM. Actually, I want the result to be 18 hours, but I got the result in 6 hours. Anyone can help me to solve this problem. Thanks in advance.


Solution

  • I could not find a better solution to this problem. So I do it my own way.

    here is the code,

    if($carbon_startDate > $carbon_edate){
        $date= Carbon::now()->format('Y-m-d');
        $start_time = Carbon::parse($working_time['start_time'])->format(' H:i:s');
        $first_time = $date.$start_time;
    
        $date2= Carbon::now();
        $next_date = $date2->addDays(1)->format('Y-m-d');
        $end_time = Carbon::parse($working_time['end_time'])->format(' H:i:s');
        $last_time = $next_date.$end_time;
        $totalDuration = Carbon::parse($first_time)->diffInHours($last_time);
     }else{
        $totalDuration = Carbon::parse($carbon_startDate)->diffInHours($carbon_edate);
        $totalDuration= round($totalDuration/$min_duration);
       }