Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 Time Difference

I have an application which on sign in records in time and on sign out records out time.

My table has IN_TIME & OUT_TIME

Example of data within those columns:

IN_TIME = 16:06:46

OUT_TIME = 16:08:07

I have a controller which to my blade template file is showing all attedances for a given person, what I want to do is show the time difference between the two.

See below my current code which currently shows 0

**Time onsite:** {{ date('G:i', strtotime($attrec->out_time)) - date('G:i', strtotime($attrec->in_time)) }}

Is there a reason why I can't get the right figure?

like image 328
Dev.W Avatar asked Jan 05 '16 16:01

Dev.W


1 Answers

You're converting the timestamps to formatted strings and trying to compute the difference between the strings. Instead you should compute the difference between the results of each datetotime (which return UNIX timestamps that are essentially seconds) and then format that result:

{{ date('G:i', strtotime($attrec->out_time) - strtotime($attrec->in_time)) }}

You can also use Carbon by doing the following:

{{ (new Carbon($attrec->out_time))->diff(new Carbon($attrec->in_time))->format('%h:%I') }}

This uses method diff inherited from DateTime, which returns a DateInterval instance. The formatting characters for DateInterval::format are different from the ones used by date. That's why the formatting string is %h:%I, which is the equivalent of G:i.

The above code will output:

0:01

Because you chose to format the hour without leading zeros, and the difference between the two timestamps is one minute (and some spare seconds that are not shown because they are not included in the formatting string).

like image 81
Bogdan Avatar answered Sep 28 '22 16:09

Bogdan