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?
3 Answers
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.)

- 50,943
- 13
- 104
- 142
-
This hack seems to be the best bet right now. I need to pass the milliseconds into Date.UTC JavaScript function. – ChaosMaker Jan 28 '12 at 05:55
-
Given that Javascript also uses dynamic typing, you could do the string concat on the client side as well. – Charles Jan 28 '12 at 05:59
-
Okay. Thanks! This did get me somewhere, though now I am now stuck at another point. – ChaosMaker Jan 28 '12 at 06:33
-
@Charles simplest solutions i've seen to multiply time stamps by 1000. +1 – Anagio Sep 11 '13 at 22:03
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, '.', '');

- 429
- 2
- 6
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:
-
Thanks, but I am using a portable WAMP Server, which I believe doesn't have all the PHP libraries included in it. – ChaosMaker Jan 28 '12 at 05:56
-
Is it a Windows-based WAMP server? If so, BC Math is built-in: http://www.php.net/manual/en/bc.installation.php – Amber Jan 28 '12 at 05:59
-