How to generate millisecond timestamp in PHP?

Asked

Viewed 3,981 times

4

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

echo time() // 1420996448

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

1 answer

5


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

round(microtime(true) * 1000);

As the function microtime() by default returns a string in the quirky format "ms seg", we can pass the parameter true for it, which makes the returned value a float in format: seg.ms.

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

Example of function above dismembered for better understanding:

microtime();                   // 0.68353600 1420997025
microtime(true);               // 1420997065.6835
microtime(true) * 1000;        // 14209970656835.3
round(microtime(true) * 1000); // 14209970656835

Browser other questions tagged

You are not signed in. Login or sign up in order to post.