Convert microtime(true) to javascript date object

923 Views Asked by At

Can the value of PHP's microtime(true) be converted to a javascript date object, and the accuracy to be preserved ?

1

There are 1 best solutions below

2
jszobody On BEST ANSWER

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.

  1. microtime(true) returns time in seconds, accurate to microseconds. You have to multiple this by 1000 to have a millisecond value for your Date object.
  2. 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.)