PHP milliseconds timestamp as an integer

June 4, 2016

There is no native function for a unix timestamp in milliseconds, only 'time()' which returns seconds since epoch and 'microtime()', which returns microseconds since the current second. Although you can use 'microtime(true)', but it returns a float that can not guarantee precision. Or just 'microtime()' and explode the string.

Custom function

In order to use this function your PHP engine has to be an 64 bit build. On 32 bit builds it will overflow and always return 2147483647, the biggest number that can be contained in a 32 bits. The Windows XAMPP build for example is 32 bit, and will not be able to produce the wanted result.

PHP 7

This function has its return type declared.

function timestamp_ms(): int {
	$times = gettimeofday();
	$seconds = strval($times["sec"]);
	$milliseconds = strval(floor($times["usec"]/1000));
	$missingleadingzeros = 3-strlen($milliseconds);
	if($missingleadingzeros >0){
		for($i = 0; $i < $missingleadingzeros; $i++){
			$milliseconds = '0'.$milliseconds;
		}
	}
	return intval($seconds.$milliseconds);	
} 

PHP 5

function timestamp_ms() {
	$times = gettimeofday();
	$seconds = strval($times["sec"]);
	$milliseconds = strval(floor($times["usec"]/1000));
	$missingleadingzeros = 3-strlen($milliseconds);
	if($missingleadingzeros >0){
		for($i = 0; $i < $missingleadingzeros; $i++){
			$milliseconds = '0'.$milliseconds;
		}
	}
	return intval($seconds.$milliseconds);	
}

Breakdown

First of we create a variable with 'gettimeofday()', which returns an array with the following indexes; 'sec' an integer that contains seconds since unix epoch, just like 'time()', and 'usec' which contains an integer that holds the microseconds passed since the beginning of the second.

We convert those integers to strings first, so we can join them up easily. This is done by the 'strval()' functions. To achieve the milliseconds we first divide the returned microseconds by 1000, and round the number down with 'floor()'.

Then we check if the microseconds is missing leading zeros, if so, we add them with the for loop.

And at the return we join the two strings together and typecast them to an integer with 'intval()'.

Afterword

Since it's not a native function, and does a lot of typecasting causing serious overhead, it will not be high performance code, not that PHP is fast itself but still.

Talking about performance, we could have used 'microtime()', explode the result and apply the same logic, which maybe a tad faster.

Read also

How to fix a slow performing xampp php 7
Generate SHA1 hash of a file in Golang example
Generate MD5 hash of a file in Golang
Comments
Tags