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?
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:You can also use
Carbon
by doing the following:This uses method
diff
inherited fromDateTime
, which returns aDateInterval
instance. The formatting characters forDateInterval::format
are different from the ones used bydate
. That's why the formatting string is%h:%I
, which is the equivalent ofG:i
.The above code will output:
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).
I may be wrong, but it's probably that arithmetic operations are undefined on the output of
date
. I'm not familiar with PHP but bash for instance will apply a numeric value of "0" to anything that's not a number that you try to add. So if you didyou'd get 5. In this case you'd have two objects evaluated as 0 giving
0 + 0 = 0
There's a question Here that addresses time arithmetic in PHP. Hopefully that will set you on the best way to achieve what you want!