Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current timestamp with milliseconds [duplicate]

I want to get current timestamp with milliseconds in PHP something like below, in JavaScript I use Date.now()

1436030635348

I tried something like below:

$time = str_replace(".","",microtime(true)); 

But sometime it is not working properly. Like it prints one or two digits less.

like image 678
Vishnu Avatar asked Jul 04 '15 17:07

Vishnu


2 Answers

It can print less digits, because it is a float value. So if you get 1234.0005, that `.0005 actually means 500 microseconds. The zeroes after the 5 are lost because it's still an unformatted float value.

The function microtime is based on the system call gettimeofday(), which also isn't accurate to the microsecond. Commonly it's accurate to 10 microseconds. See also Linux - Is gettimeofday() guaranteed to be of microsecond resolution.

-edit- I see the specs in your question have changed from microseconds to milliseconds.

To get the float value you have as an integer, you can multiply by a value. The float value represents seconds. Multiply by 1000 to get milliseconds or 1,000,000 to get microseconds. Since the specs (now) say milliseconds, you should multiply by 1000. 10k will give you accuracy of 1/10ms = 100μs. A millisecond is one thousandth of a second. A microsecond is one millionth of a seconds.

Long story short, to get the time in integer milliseconds, use this:

$milliseconds = intval(microtime(true) * 1000);

Note: there is a reason why you get the time as a string or a float by default. The reason is that on 32 bit systems, PHP's integer is also 32 bits and is not large enough to contain the timestamp including milliseconds and microseconds. So this solution will only work well on a 64 bit system.

like image 148
GolezTrol Avatar answered Oct 21 '22 20:10

GolezTrol


$timeStampData = microtime();
list($msec, $sec) = explode(' ', $timeStampData);
$msec = round($msec * 1000);

$result = $sec . $msec;

Something like this

But note, that js date.now() return time in MILLIseconds, not MICROseconds

like image 35
Valinurov Alexander Avatar answered Oct 21 '22 19:10

Valinurov Alexander