Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - hours difference (HH:MM format)

Tags:

php

time

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!

like image 700
Nick Avatar asked Dec 01 '22 22:12

Nick


1 Answers

function timeDiff($firstTime,$lastTime) {
    $firstTime=strtotime($firstTime);
    $lastTime=strtotime($lastTime);
    $timeDiff=$lastTime-$firstTime;
    return $timeDiff;
}

echo (timeDiff("10:00","12:00")/60)/60;

Originally wrote this here: https://ao.ms/how-to-get-the-hours-difference-in-hhmm-format-in-php/

like image 123
AO_ Avatar answered Dec 29 '22 15:12

AO_