Can the value of PHP's microtime(true)
be converted to a javascript date object, and the accuracy to be preserved ?
Asked
Active
Viewed 804 times
0

Alex
- 66,732
- 177
- 439
- 641
-
1ECMAScript Dates use a time value that is milliseconds, so you can't preserve microsecond precision unless you keep track of it yourself. – RobG Jan 05 '19 at 04:04
1 Answers
3
You can easily use the output of microtime
to create a JavaScript Date object, like this:
new Date(<?php echo microtime(true) * 1000 ?>)
Couple things to note here though.
microtime(true)
returns time in seconds, accurate to microseconds. You have to multiple this by 1000 to have a millisecond value for yourDate
object.- You are only then preserving millisecond precision, not the entire microsecond precision. JavaScript's
Date
does not support sub-millisecond precision.
(Also, I assume you'll pass the microtime value from the server some other way, hopefully you're not actually spitting out PHP in the middle of your JavaScript code.)

jszobody
- 28,495
- 6
- 61
- 72
-
@RobG Right, the _output_ of `microtime(true)` needs to be multiplied by 1000 to get milliseconds. My original answer was not very clear on that, I updated. Thanks! – jszobody Jan 06 '19 at 12:07
-
Ok. The original seconds value might be "accurate to microseconds" but a value can't be more accurate than its highest precision, which is seconds. It can't gain accuracy just by adding zeros (despite [*php.net*](http://php.net/manual/en/function.microtime.php) saying it's "accurate to the nearest microsecond"). ;-) – RobG Jan 06 '19 at 23:11