sara sara - 7 months ago 346
PHP Question

how to display php microtime as min: sec?

I display the code execution time in seconds using:

$time_start = microtime(true);
// code here
$time_end = microtime(true);
$time = ($time_end - $time_start);
$time = number_format((float)$time, 3, '.', '');
echo "Process Time: {$time} sec";


I got for example:

9.809 sec


I want to display the execution as:
min : sec
, with sec unit if the min <1 and min unit if min >1.
I have no issue do the unit job but, microtime gives the time in millisecond how can I get the previous output as:

00:09 sec or 03:50 min


Solution:
either:

date('i:s', (int) $time);


or:

$minutes = floor($time / 60);
$seconds = $time % 60;

$minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
$seconds = str_pad($seconds, 2, '0', STR_PAD_LEFT);

echo "Process Time: $minutes:$seconds";


Thanks all

Answer

a solution without using a date-formatter - doing it all by yourself:

$minutes = floor($time / 60);
$seconds = $time % 60;

$minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
$seconds = str_pad($seconds, 2, '0', STR_PAD_LEFT);

echo "Process Time: $minutes:$seconds";

note: this also works if minutes are equal to or greater than 60. even if your minutes are greater than 99. the latter will need more than two spaces tho (outputs 120:00 for 2 hours for example).

Comments