note 124984 added to function.microtime
| From: | shdwlynxjunk.yahoo.com via php-notes | Date: | Thu, 07 May 2020 19:40:45 +0000 |
| Subject: | note 124984 added to function.microtime | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-214590@lists.php.net to get a copy of this message | ||
It is important to note that microtime(TRUE) does NOT always return a float (at least in PHP 5.x; I
have not tested 7.x). If it happens to land on an exact second, it returns an integer instead.
Here is some simple code to illustrate this:
<?php
for ($i = 0; $i < 5000; $i++) {
echo microtime(TRUE) . "\n";
usleep(100); // Adjust this if your PC is too fast/slow
}
?>
When you run this at a command line, you'll see output like this (and you'll know EXACTLY
when I ran this):
1588881290.9992
1588881290.9994
1588881290.9996
1588881290.9998
1588881291 <-- Look, Ma, an integer!
1588881291.0002
1588881291.0004
1588881291.0006
1588881291.0008
Why does this matter? Because if you want to format microtime into a very friendly but exact
date/time, this popular code will fail on exact seconds (but works great otherwise):
<?php
$raw_time = DateTime::createFromFormat('U.u', microtime(TRUE)); // This line will not
create an object when microtime returns an integer because it depends on the number being a float,
including a decimal point!
$today = $raw_time->format('Y-m-d H:i:s.u'); // This will die when format is
attempted on a non-object
?>
The fix is to format the microtime output to force it to always be a float:
<?php
$utime = sprintf('%.4f', microtime(TRUE));
$raw_time = DateTime::createFromFormat('U.u', $utime);
$today = $raw_time->format('Y-m-d H:i:s.u');
?>
Paraphrasing the characters on Silicon Valley, "Always Float! Always Float! Always
Float!"
----
Server IP: 45.112.84.4
Probable Submitter: 38.142.137.34 (proxied: 24.14.82.234)
----
Manual Page -- http://php.net/manual/en/function.microtime.php
Edit -- https://master.php.net/note/edit/124984
Del: integrated -- https://master.php.net/note/delete/124984/integrated
Del: useless -- https://master.php.net/note/delete/124984/useless
Del: bad code -- https://master.php.net/note/delete/124984/bad+code
Del: spam -- https://master.php.net/note/delete/124984/spam
Del: non-english -- https://master.php.net/note/delete/124984/non-english
Del: in docs -- https://master.php.net/note/delete/124984/in+docs
Del: other reasons-- https://master.php.net/note/delete/124984
Reject -- https://master.php.net/note/reject/124984
Search -- https://master.php.net/manage/user-notes.php