How to Get Hours Difference Between Two Dates in Laravel?

By Hardik Savani July 8, 2022 Category : Laravel

Whenever you need to get difference between two dates in hours in laravel then you can get easily using Carbon. Laravel by default provide Carbon class. Carbon class throught you can calculate difference between two dates in hours.

you can use this example with laravel 6, laravel 7, laravel 8 and laravel 9 version.

In Following example you can see, we have a two dates, first $to variable and second one $from variable. Carbon class diffInhours function using you can get difference between two dates. I hope you will find your solution.

Example:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Carbon\Carbon;

class DemoController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

$to = Carbon::createFromFormat('Y-m-d H:s:i', '2015-5-5 3:30:34');

$from = Carbon::createFromFormat('Y-m-d H:s:i', '2015-5-5 9:30:34');

$diff_in_hours = $to->diffInHours($from);

dd($diff_in_hours);

}

}

Output

6

I hope it can help you...

Tags :