Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current time in milliseconds in PHP?

time() is in seconds - is there one in milliseconds?

like image 214
COMer Avatar asked Sep 07 '10 07:09

COMer


People also ask

How do you read Microtime?

microtime() returns the number of seconds since the "epoch time" with precision up to microseconds with two numbers separated by space, like... The second number is the seconds (integer) while the first one is the decimal part. Note that both $mt[1] and the result of round are casted to int .

What is Microtime PHP?

The microtime() function returns the current Unix timestamp with microseconds.

How do you get milliseconds since epoch?

The Date. now() and new Date(). getTime() calls retrieve the milliseconds since the UTC epoch. Convert the milliseconds since epoch to seconds by dividing by 1000.


2 Answers

The short answer is:

$milliseconds = round(microtime(true) * 1000); 
like image 176
laurent Avatar answered Oct 04 '22 01:10

laurent


Use microtime. This function returns a string separated by a space. The first part is the fractional part of seconds, the second part is the integral part. Pass in true to get as a number:

var_dump(microtime());       // string(21) "0.89115400 1283846202" var_dump(microtime(true));   // float(1283846202.89) 

Beware of precision loss if you use microtime(true).

There is also gettimeofday that returns the microseconds part as an integer.

var_dump(gettimeofday()); /* array(4) {   ["sec"]=>   int(1283846202)   ["usec"]=>   int(891199)   ["minuteswest"]=>   int(-60)   ["dsttime"]=>   int(1) } */ 
like image 43
kennytm Avatar answered Oct 04 '22 00:10

kennytm