microtime to seconds or hours or min conversion

basically, like this:

echo date("H:i:s",$endtime-$starttime);

$endtime-$starttime gives the duration in seconds, date is used to format the output. sounds like saving to and reading from a database isn't your problem here, so i left that out in my example. Note that you'll have to use microtime(true) to get this working, with the space-separated output of microtime() your can't do calculations that easy.

EDIT: you could do all the calculation on your own, too. it's just basic math like this:

$duration = $endtime-$starttime;
$hours = (int)($duration/60/60);
$minutes = (int)($duration/60)-$hours*60;
$seconds = (int)$duration-$hours*60*60-$minutes*60;

microtime to seconds or hours or min conversion?

microtime is the name of the php function that return a measure of time in microseconds and basically microseconds can be converted to:


    1 milliseconds = 1,000 microseconds
    1 second       = 1,000,000 microseconds
    1 minute       = 60,000,000 microseconds
    1 hour         = 3,600,000,000 microseconds


    or


    1 microsecond = 0.001 milliseconds
    1 microsecond = 0.000001 seconds
    1 microsecond = 0.0000000166666667 minutes
    1 microsecond = 0.000000000277777778 hours


function formatPeriod($endtime, $starttime)
{

  $duration = $endtime - $starttime;

  $hours = (int) ($duration / 60 / 60);

  $minutes = (int) ($duration / 60) - $hours * 60;

  $seconds = (int) $duration - $hours * 60 * 60 - $minutes * 60;

  return ($hours == 0 ? "00":$hours) . ":" . ($minutes == 0 ? "00":($minutes < 10? "0".$minutes:$minutes)) . ":" . ($seconds == 0 ? "00":($seconds < 10? "0".$seconds:$seconds));
}

Tags:

Php