Jump to content

time calculation problem in php


Recommended Posts

First convert to seconds

 

  /**
   * Convert H:i:s (HH:MM:SS) into seconds
   *
   * @param string $t
   * @return integer
   */
  function convertTimeToSeconds($t) {
  	$hrs=intval(substr($t,0,2))*3600;  //extract HH:mm:ss
  	$min=intval(substr($t,3,2))*60;    //extract hh:MM:ss
  	$sec=intval(substr($t,6,2));       //extract hh:mm:SS
  	return ($hrs+$min+$sec);
  }

 

You'll get the time returned as an integer - then convert to a human time.

$timeA=convertTimeToSeconds('00:00:10');
$timeB=convertTimeToSeconds('50:00:00');
$newTime=$timeB-$timeA;
$hours=floor($newTime/3600);
$minutes=floor($newTime/60);
$seconds=$newTime%60;
echo ($hours<10 ? '0' : '').$hours.':'.($minutes<10 ? '0' : '').$minutes.':'.($seconds<10 ? '0' : '').$seconds;

 

That will also format the result to two digits per part if either is lower than 10 which would need a leading 0 (ie. 5 would now be 05)

function convertTimeToSeconds($t) {

$hrs=intval(substr($t,0,2))*3600; //extract HH:mm:ss

$min=intval(substr($t,3,2))*60; //extract hh:MM:ss

$sec=intval(substr($t,6,2));   //extract hh:mm:SS

return ($hrs+$min+$sec);

}

 

$t1=convertTimeToSeconds('30:00:00');

echo "<hr>".$t1."<hr>";

$t2=convertTimeToSeconds('12:00:00');

echo "<hr>".$t2."<hr>";

$newTime=$t1-$t2;

echo "<hr>".$newTime."<hr>";

$hours=floor($newTime/3600);

$minutes=floor($newTime/60);

$seconds=$newTime%60;

echo ($hours<10 ? '0' : '').$hours.':'.($minutes<10 ? '0' : '').$minutes.':'.($seconds<10 ? '0' : '').$seconds;

 

i m using above code as described in previous thread, but it gives wrong output. it also show 18 minute difference.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.