A tutorial to determine the duration between the start date ($date1) and the end date ($date2) in years, months, hours, minutes and seconds in a Laravel project.

🌍 The French version of this publication : Comment calculer la durée entre deux dates dans Laravel

To illustrate the process of calculating the time elapsed between two dates, we will look at the created_at and updated_at fields of the model (for example, App\Models\User.php in your Laravel project). These fields indicate respectively the date of creation and last update of the model.

To find the time interval between these two dates, we will use the diff() method:

class User extends Authenticatable
{
    public function getDurationAttribute () {

        $date1 = $this->created_at;

        $date2 = $this->updated_at; 

        $duration = $date1->diff($date2); // Difference between the dates

        return $duration; // Object DateInterval

    }
}

The method getDurationAttribute() returns a DateInterval object. This object can be formatted in year, month, day, hour, minute and second using the format() method, then displayed on the Blade view:

{{ $user->duration->format("%y years %m months %d days %h hours %i minutes %s seconds") }}

This code will display a string like this:

1 years 3 months 16 days 18 hours 33 minutes 12 seconds

Acceptable formats are described in the DateInterval documentation.

🖐 Note: By default, the created_at and updated_at attributes are Illuminate\Support\Carbon objects. If it is another time field (date/time), you will need to convert it to a Carbon object via the $casts property of the model:

protected $casts = [
    "start_time" => "datetime",
    "end_time" => "datetime"
];

Be well 😉