Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I was measuring some curl requests and I used microtime(true). The example output would be 3.1745569706

This is 3.1745569706 seconds. I want to convert that to a somewhat more readable format, let's say 00:00:03:17455 (HOURS:MINUTES:SECONDS:MILLISECONDS)

$maxWaitTime = '3.1745569706'; echo gmdate("H:i:s.u", $maxWaitTime);  // which returns 00:00:01.000000  echo date("H:i:s.u" , $maxWaitTime) // which returns 18:00:01.000000 

That looks wrong. I'm not quite sure what I'm missing here.

How do I convert microtime() to HH:MM:SS:UU ?

like image 965
ProDraz Avatar asked May 29 '13 22:05

ProDraz


People also ask

What is a Microtime?

Definition of microtime : a very short interval of time (as 0.01 millionth of a second) microtime photography.

What is Microtime function in PHP?

PHP microtime() function returns the current Unix timestamp. By default this returns a string value in the form msec sec. If you pass the boolean value true as a parameter to this method, it returns the current time in seconds since the Unix epoch accurate to the nearest microsecond.


2 Answers

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 usec  print 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 . 
like image 101
edwardmp Avatar answered Oct 29 '22 08:10

edwardmp


<?php  function 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 
like image 37
Yogus Avatar answered Oct 29 '22 07:10

Yogus