A method of subtracting a string of numbers which are times (HH:MM:SS) in PHP? A method of subtracting a string of numbers which are times (HH:MM:SS) in PHP? codeigniter codeigniter

A method of subtracting a string of numbers which are times (HH:MM:SS) in PHP?


this would be like

    //function to convert seconds into hour:minute:second    function sec2hms ($sec, $padHours = false)     {        // start with a blank string        $hms = "";         // do the hours first: there are 3600 seconds in an hour, so if we divide         // the total number of seconds by 3600 and throw away the remainder, we're         // left with the number of hours in those seconds         $hours = intval(intval($sec) / 3600);          // add hours to $hms (with a leading 0 if asked for)         $hms .= ($padHours)          ? str_pad($hours, 2, "0", STR_PAD_LEFT). ":"         : $hours. ":";         // dividing the total seconds by 60 will give us the number of minutes         // in total, but we're interested in *minutes past the hour* and to get         // this, we have to divide by 60 again and then use the remainder         $minutes = intval(($sec / 60) % 60);          // add minutes to $hms (with a leading 0 if needed)         $hms .= str_pad($minutes, 2, "0", STR_PAD_LEFT). ":";        // seconds past the minute are found by dividing the total number of seconds        // by 60 and using the remainder        $seconds = intval($sec % 60);         // add seconds to $hms (with a leading 0 if needed)        $hms .= str_pad($seconds, 2, "0", STR_PAD_LEFT);       // done!       return $hms;     }    $subtracted_time = strtotime($time2) - strtotime($time1); //gives difference in seconds    echo(sec2hms($subtracted_time));

function sec2hms source http://www.laughing-buddha.net/php/lib/sec2hms/


I would use the strtotime() function to convert the times to UNIX time values. Then, you can subtract the two values because they'll be integers and then use the date() function to format the difference in the way you want.


This is my suggestion (working PHP code):

$time1 = '12:45:03';$time2 = '14:03:48';$timelength = strtotime( $time2 ) - strtotime( $time1 );$hours = intval( $timelength / 3600 );$minutes = intval( ( $timelength % 3600 ) / 60 );$seconds = $timelength % 60;echo str_pad( $hours, 2, '0', STR_PAD_LEFT ) . ':' . str_pad( $minutes, 2, '0', STR_PAD_LEFT ) . ':' . str_pad( $seconds, 2, '0', STR_PAD_LEFT );

Output:

01:18:45