What is the maximum date precision in PHP?

PHP has several ways to create timestamps. What is the most accurate timestamp?

-one
php time
Dec 30 '16 at 3:41
source share
2 answers

If by exact you mean the least possible time, according to the PHP manual, you can get Unix timestamps in microseconds. So far, your operating system supports the gettimeofday() system call.

microtime ()

+4
Dec 30 '16 at 3:48
source share

The general microtime(true) method, however, is probably not the most accurate option.

  • DateTime by default is not very good and will give you seconds.

     $ php -r 'echo (new \DateTime())->format("Uu");' 1483069259.000000 
  • microtime(true) better and you get approximate microseconds, but the accuracy of the float will do some rounding.

     $ php -r 'echo microtime(true);' 1483069130.6427 
  • gettimeofday() better and gives you the exact microsecond. You can use microseconds(false) , but processing the output is more complicated.

     $ php -r 'echo implode(".", array_slice(gettimeofday(), 0, 2));' 1483070039.572630 

Thus, the best available instance is \DateTime , with full precision in microseconds:

 \DateTime::createFromFormat("Uu", implode(".", array_slice(gettimeofday(), 0, 2))) 
+1
Dec 30 '16 at 4:03
source share



All Articles