php time arithmetic and time difference between to times

Thursday, September 22, 2011

Working with time different is very interesting in PHP, here is a function to find out the time difference and give the output in time format either it can be a 12hr/ 24hrs format. let us write this function to find out the
time arithmetic and time difference between to times using PHP. This function is very useful for compare the duration between two times, such employee work entry system, total hours of work

We can find the difference between Two time eg: 10:00:00 AM to 01:00:00 PM or 10:00:00 AM to 13:00:00 PM.

# Desc: function to return Time difference in between the two Times in a day
# Parm: Start_time end Time as 12hr/24hr format within single day
# Return: duration in time format: hh:mm:ss
function time_difference($start_time="11:00:00",$end_time="12:00:00")
list($h1,$m1,$s1)    =    split(':',$start_time);  
$startTimeStamp    =    mktime($h1,$m1,$s1,0,0,0);

list($h2,$m2,$s2)    =    split(':',$end_time);   

//check end time is in 12 hrs format:
if($h2 < $h1)

$endTimeStamp    =    mktime($h2,$m2,$s2,0,0,0); 
$time=abs($endTimeStamp - $startTimeStamp);

$value = array(
"hours" => "00",
"minutes" => "00",
"seconds" => "00"


if($time >= 3600){
$value["hours"] = sprintf("%02d",floor($time/3600));
$time = ($time%3600);
if($time >= 60){
$value["minutes"] = sprintf("%02d",floor($time/60));
$time = ($time%60);

$value["seconds"] = sprintf("%02d",floor($time));

return implode(":",$value); 

echo time_difference("11:45:00","01:30:00");
echo "<br />";
echo time_difference("13:00:00","15:00:00");

// 01:45:00
// 02:00:00


No comments:

Post a Comment