Blues Clues
Blues Clues

Reputation: 1848

How to get the difference of created_at and updated_at in laravel 5.1

I've researched about on internet but what I found is only getting the past time (e.g. 4mins ago), What I want is to get the difference from created_at and updated_at in my database and like so, 3days 3hrs 23mins 30sec and if there's no mins or hrs, just output the 3days 3hrs 30sec or 3days 23mins 30sec.

What I have:

view

@foreach($submits as $submit)
   {{ $submit->pivot->created_at }} // to get the created_at
   {{ $submit->pivot->updated_at }} // to get the updated_at
@endforeach

Upvotes: 0

Views: 2076

Answers (1)

noufalcep
noufalcep

Reputation: 3536

You can find days, hours, minutes and seconds by using this function.

public function getDifference($created_at, $updated_at) {
    $days = $created_at->diffInDays($updated_at);
    $hours = $created_at->diffInHours($updated_at->subDays($days));
    $minutes = $created_at->diffInMinutes($updated_at->subHours($hours));
    $seconds = $created_at->diffInSeconds($updated_at->subMinutes($minutes));
    return CarbonInterval::days($days)->hours($hours)->minutes($minutes)->seconds($seconds)->forHumans();
}

Output

3 days 3 hours 23 minutes 30 seconds

Upvotes: 1

Related Questions