How to Get The Time Difference Between Two Dates in Laravel

AuthorSumit Dey Sarkar

Pubish Date22 Mar 2023

categoryLaravel

In this tutorial we will learn how to get the time difference between two dates in laravel .

 

How to get the time difference between two dates in laravel

In Laravel, you can use the built-in Carbon library to get the time difference between two dates.

 

Here's an example:

$date1 = \Carbon\Carbon::parse('2023-03-21 12:00:00');
$date2 = \Carbon\Carbon::parse('2023-03-22 12:00:00');
$diff = $date1->diffForHumans($date2);

echo $diff;

 

In the above example, we have used the `Carbon` class to create two objects representing two different dates. We have then called the `diffForHumans()` method on the first `Carbon` object, passing the second `Carbon` object as an argument. This returns a human-readable string representing the time difference between the two dates.

 

The `diffForHumans()` method automatically determines the appropriate time unit (e.g. seconds, minutes, hours, days) based on the time difference between the two dates. It also uses language-specific phrasing to provide a natural language representation of the time difference.

 

You can customize the output format using various options available with the `diffForHumans()` method. For example, you can use the `short` option to get a shorter output, or the `syntax` option to switch between "from-now" and "ago" phrasing.

 

Comments 0

Leave a comment