skip to Main Content

I want to check difference between two times in Laravel (the day is not needed)

Carbon::createFromTimeString($this->debut)
        ->diffInHours(Carbon::createFromTimeString($this->fin))

if $this->debut = '08:00:00' and $this->fin = '02:00:00' the expected result is 18 but I have 6

How can I get the correct difference please

2

Answers


  1. Anyway you have to set date at least relatively for the correct calculation:

    $this->debut = Carbon::today()->hour(8);
    $this->fin = Carbon::tomorrow()->hour(2);
    
    $diff = $this->debut->diffInHours($this->fin); // 18
    
    Login or Signup to reply.
  2. The condition should be that the time difference should always be positive. If the second parameter of Carbon::diffInHours is set to false, the result is not absolute. In this case, the intermediate result is -6. If the difference is negative, 24 hours are added.

    $start = '08:00:00';
    $end = '02:00:00';
    $hours = Carbon::create($start)->diffInHours($end, false);
    if($hours < 0) $hours += 24;
    echo $hours;  //18
    

    Try them yourself.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search