4

I am trying to get epoch time for specific dates in milliseconds. However, if I get the time in seconds and multiply by 1000, I get a value in this format - 1.3E+12. I would like the return value to be in the format like 1300000000000. Is this possible?

ChaosMaker
  • 43
  • 2
  • 7

3 Answers3

6

It looks like you're using PHP on a 32-bit platform.

Right now, the Unix epoch timestamp (what you get from time()) is a 31-bit signed integer. On 32-bit platforms, PHP can not natively support integers larger than 32 bits. When you try to multiply it by 1000, the result is a 41-bit integer. Because PHP can't do that, it transforms the integer into a floating point number. As a side effect, you see the brief scientific notation when you echo it.

Because PHP also can't represent a normal timestamp with milliseconds (not even with a DateTime object), your best bet here is to perform another transformation of the integer, into a string.

echo time() . '000';

It's an ugly hack, but you will produce a string that looks exactly like the millisecond-based epoch timestamp you're expecting. As long as you don't expect to perform math on it, you should be OK. Given that you're probably producing this for some Java-based web service or another, you can probably get away with it. (If you control both ends of the web service, consider switching over to ISO 8601 datetimes for superior interoperability.)

Charles
  • 50,943
  • 13
  • 104
  • 142
1

If you just want to get away from scientific notation, then you can change the formatting of the number by using number_format function.

$epoch_milliseconds = time() * 1000;
echo number_format($epoch_milliseconds, 0, '.', '');
fixlr
  • 429
  • 2
  • 6
0

You may want to look into PHP's libraries for handling large numbers if you actually need to work with the timestamp after generating it:

Working with large numbers in PHP

Community
  • 1
  • 1
Amber
  • 507,862
  • 82
  • 626
  • 550