How to generate timestamp in milliseconds in PHP?

4

The time() function of PHP generates a UNIX timestamp in seconds, for example:

echo time() // 1420996448

But I would like to generate a Unix timestamp also with milliseconds, how can I do this?

    
asked by anonymous 11.01.2015 / 18:23

1 answer

5

Using the microtime() function combined with round() you can return a timestamp in milliseconds, eg:

round(microtime(true) * 1000);

Because the microtime() function returns a string in the peculiar format "ms seg" , we can pass the true parameter to it, which causes the returned value to be a float in format: seg.ms .

With float , you can do a simple calculation by multiplying it by a thousand ( 1000 ) and rounding the final result so as to always return a timestamp in int format.

Example of the above function dismembered for better understanding:

microtime();                   // 0.68353600 1420997025
microtime(true);               // 1420997065.6835
microtime(true) * 1000;        // 14209970656835.3
round(microtime(true) * 1000); // 14209970656835
    
11.01.2015 / 18:23