Search code examples
phphourminute

Hour, Minute difference in php


I am looking a solution in Php.

I have a total time for a task in hh:mm:ss format. (Date is not important). and I am entering each working time also in hh:mm:ss format. Now I have to find out the remain hours in hh:mm:ss format.

Example

16:00:00 is the assigned hours to do a task. In different dates one employee worked 13:15:00 hours Now I need the remaining hours as 2:45:00 in format.

If date is attached then we can do like

datetime1 = new DateTime('2014-02-11 04:04:26 AM');
$datetime2 = new DateTime('2014-02-11 05:36:56 AM');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%h')." Hours ".$interval->format('%i')." Minutes";

In my case there is no date. is there any functionality in PHP to find this type of hh:mm:ss difference?


Solution

  • Convert your HH:MM:SS format to a duration in seconds, subtract them, format them back to HH:MM:SS:

    function str_to_seconds($duration) {
        list($h, $m, $s) = explode(':', $duration);
        return $s + ($m * 60) + ($h * 3600);
    }
    
    function seconds_to_str($seconds) {
        return sprintf('%02d:%02d:%02d', $seconds / 3600, $seconds / 60 % 60, $seconds % 60);
    }
    
    echo seconds_to_str(str_to_seconds('16:00:00') - str_to_seconds('13:15:00'));