I'm trying to calculate the shift patterns of people who work here, subtracting the start time from the end time works for the most part, but not if they're working overnight. For example someone working from 10pm to 6am
would be displayed as:
22:00 - 06:00
I'd like that to return 8 hours
, but I just can't figure out the best way of doing it.
Annoyingly, I'm then going to have to do the exact same thing in Javascript, so I hope I can get my head around the logic for this. Taking away one date from the other just doesn't work in this case...
Any help would be much appreciated, thank you!
Working AND most easy sample :
Originally wrote this here: http://andrewodendaal.com/php-hours-difference-hhmm-format/
You can look into
date_diff
, which is an alias of this function:http://www.php.net/manual/en/datetime.diff.php
MySQL also has a
DATEDIFF()
function, so if you are grabbing them from a database you can do it directly from SQL (I know you didn't specify, but I just wanted to mention this).You can use the function mktime (http://php.net/manual/en/function.mktime.php) to return the number of seconds and subtract the two dates in integer format.
without some date function:
Old school, with string manipulation and math:
With date/time functions:
Devilish gotcha for any solution using date/time functions:
If you do not explicitly specify the offset for
$start
and$end
, and we are talking about a night shift, and the code is run on the day where daylight savings time starts or ends the results would be off by whatever the DST offset is.This is true for any solution that uses
DateTime
,strtotime
, etc.