Laravel 5 Time Difference

2019-05-15 23:33发布

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?

2条回答
够拽才男人
2楼-- · 2019-05-16 00:06

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).

查看更多
一夜七次
3楼-- · 2019-05-16 00:06

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 did

"hello" + 5

you'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!

查看更多
登录 后发表回答