Sometimes there is a need to calculate the difference between two dates or timestamps to get the time difference between in hours, minutes seconds, etc, For this, Carbon library also has functions like diffInHours
, diffInMinutes
and diffInSeconds
, Which you can use to do it.
How to Calculate Time Difference Between Two Dates in Hours, Minutes and Seconds
Here are three different approaches to compare two carbon date time and get the difference between hours, minutes and seconds in laravel:
Approach 1: Get the Hours Difference Between Two Carbon Dates in Laravel
Here is the code to calculate hours difference between two date time carbon in laravel:
<?php namespace App\Http\Controllers; use Carbon\Carbon; class CarDatesController extends Controller { public function calculateDiffInHours() { $dateTime1 = Carbon::createFromFormat("Y-m-d H:i:s", "2025-06-06 00:00:00"); $dateTime2 = Carbon::createFromFormat("Y-m-d H:i:s", date("Y-m-d H:i:00")); $getDiffInHours = $dateTime1->diffInHours($dateTime2); echo "carbon time diff in hours:-"; dd($getDiffInHours); } }
Approach 2: Get Minutes Difference Between Two Carbon Dates in Laravel
Here is the code to calculate time difference in minutes between two date time carbon in laravel:
<?php namespace App\Http\Controllers; use Carbon\Carbon; class CarDatesController extends Controller { public function calculateDiffInMinutes() { $dateTime1 = Carbon::createFromFormat("Y-m-d H:i:s", "2025-06-06 00:00:00"); $dateTime2 = Carbon::createFromFormat("Y-m-d H:i:s", date("Y-m-d H:i:00")); $getDiffInMinutes = $dateTime1->diffInMinutes($dateTime2); echo "carbon time diff in minutes:-"; dd($getDiffInMinutes); } }
Approach 3: Get Seconds Difference Between Two Carbon Dates in Laravel
Here is the code to calculate the seconds difference between two date time carbon in laravel:
<?php namespace App\Http\Controllers; use Carbon\Carbon; class CarDatesController extends Controller { public function calculateDiffInSeconds() { $dateTime1 = Carbon::createFromFormat("Y-m-d H:i:s", "2025-06-06 00:00:00"); $dateTime2 = Carbon::createFromFormat("Y-m-d H:i:s", date("Y-m-d H:i:00")); $getDiffInSeconds = $dateTime1->diffInSeconds($dateTime2); echo "carbon time diff in Seconds:-"; dd($getDiffInSeconds); } }
Conclusion
That’s all; you have learned how to use php carbon library functions to calculate the time difference between two dates in hours, minutes, and seconds in Laravel apps.
Reference: https://carbon.nesbot.com/docs/.