How to get current time in milliseconds in PHP?

PhpTimeMilliseconds

Php Problem Overview


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

Php Solutions


Solution 1 - Php

The short answer is:

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

Solution 2 - Php

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)
}
*/

Solution 3 - Php

Short answer:

64 bits platforms only!

function milliseconds() {
    $mt = explode(' ', microtime());
    return ((int)$mt[1]) * 1000 + ((int)round($mt[0] * 1000));
}

[ If you are running 64 bits PHP then the constant PHP_INT_SIZE equals to 8 ]


Long answer:

If you want an equilvalent function of time() in milliseconds first you have to consider that as time() returns the number of seconds elapsed since the "epoch time" (01/01/1970), the number of milliseconds since the "epoch time" is a big number and doesn't fit into a 32 bits integer.

The size of an integer in PHP can be 32 or 64 bits depending on platform.

From http://php.net/manual/en/language.types.integer.php

> The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18, except for Windows, which is always 32 bit. PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5.

If you have 64 bits integers then you may use the following function:

function milliseconds() {
    $mt = explode(' ', microtime());
    return ((int)$mt[1]) * 1000 + ((int)round($mt[0] * 1000));
}

microtime() returns the number of seconds since the "epoch time" with precision up to microseconds with two numbers separated by space, like...

0.90441300 1409263371

The second number is the seconds (integer) while the first one is the decimal part.

The above function milliseconds() takes the integer part multiplied by 1000

1409263371000

then adds the decimal part multiplied by 1000 and rounded to 0 decimals

1409263371904

Note that both $mt[1] and the result of round are casted to int. This is necessary because they are floats and the operation on them without casting would result in the function returning a float.

Finally, that function is slightly more precise than

round(microtime(true)*1000);

that with a ratio of 1:10 (approx.) returns 1 more millisecond than the correct result. This is due to the limited precision of the float type (microtime(true) returns a float). Anyway if you still prefer the shorter round(microtime(true)*1000); I would suggest casting to int the result.


Even if it's beyond the scope of the question it's worth mentioning that if your platform supports 64 bits integers then you can also get the current time in microseconds without incurring in overflow.

If fact 2^63 - 1 (biggest signed integer) divided by 10^6 * 3600 * 24 * 365 (approximately the microseconds in one year) gives 292471.

That's the same value you get with

echo (int)( PHP_INT_MAX / ( 1000000 * 3600 * 24 * 365 ) );

In other words, a signed 64 bits integer have room to store a timespan of over 200,000 years measured in microseconds.

You may have then

function microseconds() {
    $mt = explode(' ', microtime());
    return ((int)$mt[1]) * 1000000 + ((int)round($mt[0] * 1000000));
}

Solution 4 - Php

As other have stated, you can use microtime() to get millisecond precision on timestamps.

From your comments, you seem to want it as a high-precision UNIX Timestamp. Something like DateTime.Now.Ticks in the .NET world.

You may use the following function to do so:

function millitime() {
  $microtime = microtime();
  $comps = explode(' ', $microtime);

  // Note: Using a string here to prevent loss of precision
  // in case of "overflow" (PHP converts it to a double)
  return sprintf('%d%03d', $comps[1], $comps[0] * 1000);
}

Solution 5 - Php

Use microtime(true) in PHP 5, or the following modification in PHP 4:

array_sum(explode(' ', microtime()));

A portable way to write that code would be:

function getMicrotime()
{
	if (version_compare(PHP_VERSION, '5.0.0', '<'))
	{
		return array_sum(explode(' ', microtime()));
	}
	
	return microtime(true);
}

Solution 6 - Php

echo date('Y-m-d H:i:s.') . gettimeofday()['usec'];

output:

2016-11-19 15:12:34.346351

Solution 7 - Php

Shortest version of string variant (32-bit compatibile):

$milliseconds = date_create()->format('Uv');

Solution 8 - Php

This works even if you are on 32-bit PHP:

list($msec, $sec) = explode(' ', microtime());

$time_milli = $sec.substr($msec, 2, 3); // '1491536422147'
$time_micro = $sec.substr($msec, 2, 6); // '1491536422147300'

Note this doesn't give you integers, but strings. However this works fine in many cases, for example when building URLs for REST requests.


If you need integers, 64-bit PHP is mandatory.

Then you can reuse the above code and cast to (int):

list($msec, $sec) = explode(' ', microtime());

// these parentheses are mandatory otherwise the precedence is wrong!
//                  ↓                        ↓
$time_milli = (int) ($sec.substr($msec, 2, 3)); // 1491536422147
$time_micro = (int) ($sec.substr($msec, 2, 6)); // 1491536422147300

Or you can use the good ol' one-liners:

$time_milli = (int) round(microtime(true) * 1000);    // 1491536422147
$time_micro = (int) round(microtime(true) * 1000000); // 1491536422147300

Solution 9 - Php

try this:

public function getTimeToMicroseconds() {
    $t = microtime(true);
    $micro = sprintf("%06d", ($t - floor($t)) * 1000000);
    $d = new DateTime(date('Y-m-d H:i:s.' . $micro, $t));

    return $d->format("Y-m-d H:i:s.u"); 
}

Solution 10 - Php

PHP 5.2.2 <

$d = new DateTime();
echo $d->format("Y-m-d H:i:s.u"); // u : Microseconds

PHP 7.0.0 < 7.1

$d = new DateTime();
echo $d->format("Y-m-d H:i:s.v"); // v : Milliseconds 

Solution 11 - Php

$timeparts = explode(" ",microtime());
$currenttime = bcadd(($timeparts[0]*1000),bcmul($timeparts[1],1000));
echo $currenttime;

> NOTE: PHP5 is required for this function due to the improvements with > microtime() and the bc math module is also required (as we’re dealing > with large numbers, you can check if you have the module in phpinfo).

Hope this help you.

Solution 12 - Php

$the_date_time = new DateTime($date_string);
$the_date_time_in_ms = ($the_date_time->format('U') * 1000) +
    ($the_date_time->format('u') / 1000);

Solution 13 - Php

If you want to see real microseconds, you will need to change the precision setting in php.ini to 16.

After that, microsecond(true) gave me the output of 1631882476.298437.

So I thought that I need to divide the remainder (298437) with 1000, but in fact, the remainder is 0.298437 of a second. So I need to multiply that by 1000 to get the correct result.

    function get_milliseconds()
    {
        $timestamp = microtime(true);
        return (int)(($timestamp - (int)$timestamp) * 1000);
    }

Solution 14 - Php

I personaly use this:

public static function formatMicrotimestamp(DateTimeInterface $dateTime): int
{
    return (int) substr($dateTime->format('Uu'), 0, 13);
}

Solution 15 - Php

This is my implementation, should work on 32bit as well.

function mstime(){
    $mstime = explode(' ',microtime());
    return $mstime[1].''.(int)($mstime[0]*1000);
}

Solution 16 - Php

Use this:

function get_millis(){   list($usec, $sec) = explode(' ', microtime());   return (int) ((int) $sec * 1000 + ((float) $usec * 1000)); }

Bye

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCOMerView Question on Stackoverflow
Solution 1 - PhplaurentView Answer on Stackoverflow
Solution 2 - PhpkennytmView Answer on Stackoverflow
Solution 3 - PhpPaoloView Answer on Stackoverflow
Solution 4 - PhpAndrew MooreView Answer on Stackoverflow
Solution 5 - PhpAlix AxelView Answer on Stackoverflow
Solution 6 - Phpmojmir.novakView Answer on Stackoverflow
Solution 7 - PhpMilan MajerView Answer on Stackoverflow
Solution 8 - PhpGras DoubleView Answer on Stackoverflow
Solution 9 - PhpHồ Lê Thiện ThànhView Answer on Stackoverflow
Solution 10 - PhpSadeeView Answer on Stackoverflow
Solution 11 - PhpamnipponView Answer on Stackoverflow
Solution 12 - Phpuser3767296View Answer on Stackoverflow
Solution 13 - Phpdomaci_a_nasView Answer on Stackoverflow
Solution 14 - PhpWolly WombatView Answer on Stackoverflow
Solution 15 - PhpOliver M GrechView Answer on Stackoverflow
Solution 16 - PhpMIKEEEEEView Answer on Stackoverflow