Matthieu Boisjoli
Matthieu Boisjoli

Reputation: 1077

How do I get the difference of time in human readable format with Laravel 5?

I want to display the difference between the current date and time with the one stored in the updated_at column. However, I want it to be human-friendly like:

53 mins ago
2 hours ago
3 days ago

Is there a function out there that I could use to make it easier?

To be sure that you understand me, let's say I have a column (updated_at) in my database which is equal to 2015-06-22 20:00:03 and the current time is 20:00:28. Then I'd like to see:

25 mins ago

When it's higher than 59 minutes, I want to show only hours and when it's higher than 24 hours I'd like to see how many days ago.

Upvotes: 44

Views: 79710

Answers (3)

Umair Tanveer
Umair Tanveer

Reputation: 11

function timeDiff($firstTime, $lastTime): string
{
    $firstTime = strtotime($firstTime);
    $lastTime = strtotime($lastTime);

    $difference = $lastTime - $firstTime;

    $data['years'] = abs(floor($difference / 31536000));
    $data['days'] = abs(floor(($difference - ($data['years'] * 31536000)) / 86400));
    $data['hours'] = abs(floor(($difference - ($data['years'] * 31536000) - ($data['days'] * 86400)) / 3600));
    $data['minutes'] = abs(floor(($difference - ($data['years'] * 31536000) - ($data['days'] * 86400) - ($data['hours'] * 3600)) / 60));

    $timeString = '';

    if ($data['years'] > 0) {
        $timeString .= $data['years'] . " Years, ";
    }

    if ($data['days'] > 0) {
        $timeString .= $data['days'] . " Days, ";
    }

    if ($data['hours'] > 0) {
        $timeString .= $data['hours'] . " Hours, ";
    }

    if ($data['minutes'] > 0) {
        $timeString .= $data['minutes'] . " Minutes";
    }

    return $timeString;
}

Upvotes: 1

Wainaina Nik
Wainaina Nik

Reputation: 193

incase of the date is in a string format, use laravel Carbon; e.g,

 {{ \Carbon\Carbon::parse($on_revision->assignment->deadline)->diffForhumans() }}

Notice how I wrap my string in the carbon::parse()

Upvotes: 11

Burak Ozdemir
Burak Ozdemir

Reputation: 5332

By default, Eloquent converts created_at and updated_at columns to instances of Carbon. So if you are fetching the data using Eloquent, then you can do it as below.

$object->updated_at->diffForHumans();

If you want to customize the fields that will be mutated automatically, then within your model, you can customize them as you wish.

// Carbon instance fields
protected $dates = ['created_at', 'updated_at', 'deleted_at'];

Upvotes: 120

Related Questions