PHP Fatal error: Call to a member function format() on boolean
Neither example work as you have multiple errors:
- You forgot your second parameter to
Datetime::createFromFormat()
h:i:s
should beH:i:s
- Your date in the second example is separated by a
.
not a-
Fixes:
<?php
$date = "13-06-2015 23:45:52";
echo DateTime::createFromFormat('d-m-Y H:i:s', $date)->format('Y-m-d h:i:s');
$date = "10.06.2015 09:25:52";
echo DateTime::createFromFormat('d.m.Y H:i:s', $date)->format('Y-m-d h:i:s');
?>
In my case I was getting this error because I was using microtime(true)
as input:
$now = DateTime::createFromFormat('U.u', microtime(true));
In the specific moments where microtime
returns a float with only zeros as decimals, this error appeared.
So I had to verify if its decimals and add a decimal part:
$aux = microtime(true);
$decimais = $aux - floor($aux);
if($decimais<=10e-5) $aux += 0.1;
$now = DateTime::createFromFormat('U.u', $aux);
EDIT:
Due to floating point precision sometimes floor brings an incorret floor, so I had to use a more straight forward approach:
$aux = microtime(true);
$now = DateTime::createFromFormat('U.u', $aux);
if (is_bool($now)) $now = DateTime::createFromFormat('U.u', $aux += 0.001);
While others try to get this question answered with a specific use case, I think it's time to wrap it up with a general answer.
Fatal error: Uncaught Error: Call to a member function format() on bool in path/to/source/code/file.php
When this exception error is raised, it's because the format()
function gets a bad date format string. So, try to check the parameter according to https://www.php.net/manual/en/datetime.createfromformat.php#format