Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

microtime to seconds or hours or min conversion [duplicate]

Tags:

php

I have the store start time as microtime() and end time as microtime() into database.

Now I want to calculate how long the script takes the seconds/minutes/hours to execute.

How can I do in PHP?

like image 342
svk Avatar asked Jun 24 '11 12:06

svk


3 Answers

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;
like image 160
oezi Avatar answered Nov 15 '22 12:11

oezi


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

like image 25
user2754369 Avatar answered Nov 15 '22 13:11

user2754369


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));
}
like image 32
ahmed reda Avatar answered Nov 15 '22 12:11

ahmed reda