Unable to figure out the reason of failure of DateTime::createFromFormat
I've got this code snippet written by another dev
$date = DateTime::createFromFormat('U.u', microtime(TRUE));
$dateMicro = $date->format('Y-m-d H:i:s.u');
It's throwing this error:
Error: Call to a member function format() on bool
I guess which could mean createFromFormat returned false but I can't figure out why it did that.
What could be the cause of this?
Thank you for your time!
.u
format suggests that the input string contains a .
followed by (up to six) digits. You code will fail when the float returned by microtime(true)
has 0 or more than 6 digits after decimal.
You can test it with following script:
while (true) {
$time = microtime(true);
// potential fix
// $time = sprintf('%.6f', microtime(true));
echo $time , "\n";
$date = DateTime::createFromFormat('U.u', $time);
$dateMicro = $date->format('Y-m-d H:i:s.u');
}
Output
...
1642510930.9999
1642510930.9999
1642510930.9999
1642510930.9999
1642510930.9999
1642510930.9999
1642510931
PHP Fatal error: Uncaught Error: Call to a member function format() on bool in .../test.php:7
Stack trace:
#0 {main}
thrown in .../test.php on line 7