How to convert microtime() to HH:MM:SS:UU How to convert microtime() to HH:MM:SS:UU php php

How to convert microtime() to HH:MM:SS:UU


From the PHP.net article on date() which is similar to gmdate(), except that the time is returned in GMT:

Since this function only accepts integer timestamps the u format character is only useful when using the date_format() function with user based timestamps created with date_create().

Use something like this instead:

list($usec, $sec) = explode(' ', microtime()); //split the microtime on space                                               //with two tokens $usec and $sec$usec = str_replace("0.", ".", $usec);     //remove the leading '0.' from usecprint date('H:i:s', $sec) . $usec;       //appends the decimal portion of seconds

Which prints: 00:00:03.1745569706

If you want you can use round() to round the $usec var even more.

If you use microtime(true) use this instead:

list($sec, $usec) = explode('.', microtime(true)); //split the microtime on .


<?phpfunction format_period($seconds_input){  $hours = (int)($minutes = (int)($seconds = (int)($milliseconds = (int)($seconds_input * 1000)) / 1000) / 60) / 60;  return $hours.':'.($minutes%60).':'.($seconds%60).(($milliseconds===0)?'':'.'.rtrim($milliseconds%1000, '0'));}echo format_period(3.1745569706);

OUTPUT

0:0:3.174


Assuming one really cares about microseconds, which is admittedly rare, then one should not use any representation that involves floats.

Instead use gettimeofday() which will return an associative array that contains the seconds and microseconds as integers.

$g1 = gettimeofday();# execute your process here$g2 = gettimeofday();$borrow  = $g2['usec'] < $g1['usec'] ;$seconds = $g2['sec'] - $g1['sec'] - $borrow ;$micros  = $borrow*1000000 + $g2['usec'] - $g1['usec'] ;$delta   = gmdate( 'H:i:s.', $seconds ).sprintf( '%06d', $micros );