note 128901 added to datetime.createfromformat
| From: | StevenDeVolder at main dot php dot net | Date: | Wed, 20 Sep 2023 14:08:47 +0000 |
| Subject: | note 128901 added to datetime.createfromformat | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-220861@lists.php.net to get a copy of this message | ||
In the following code:
$t = microtime(true);
$now = DateTime::createFromFormat('U.u', $t);
$now = $now->format("H:i:s.v");
Trying to format() will return a fatal error if microtime(true) just so happened to return a float
with all zeros as decimals. This is because DateTime::createFromFormat('U.u',
$aFloatWithAllZeros) returns false.
Workaround (the while loop is for testing if the solution works):
$t = microtime(true);
$now = DateTime::createFromFormat('U.u', $t);
while (!is_bool($now)) {//for testing solution
$t = microtime(true);
$now = DateTime::createFromFormat('U.u', $t);
}
if (is_bool($now)) {//the problem
$now = DateTime::createFromFormat('U', $t);//the solution
}
$now = $now->format("H:i:s.v");
----
Server IP: 45.112.84.4
Probable Submitter: 45.91.157.134 (proxied: 2a02:1812:1126:5d00:7487:a569:c09a:8acd)
----
Manual Page -- https://php.net/manual/en/datetime.createfromformat.php
Edit -- https://main.php.net/note/edit/128901
Del: integrated -- https://main.php.net/note/delete/128901/integrated
Del: useless -- https://main.php.net/note/delete/128901/useless
Del: bad code -- https://main.php.net/note/delete/128901/bad+code
Del: spam -- https://main.php.net/note/delete/128901/spam
Del: non-english -- https://main.php.net/note/delete/128901/non-english
Del: in docs -- https://main.php.net/note/delete/128901/in+docs
Del: other reasons-- https://main.php.net/note/delete/128901
Reject -- https://main.php.net/note/reject/128901
Search -- https://main.php.net/manage/user-notes.php