PHP Fatal error: Call to a member function format() on boolean

83,139

Solution 1

Neither example work as you have multiple errors:

  1. You forgot your second parameter to Datetime::createFromFormat()
  2. h:i:s should be H:i:s
  3. 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');
?>

Solution 2

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);

Solution 3

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

Share:
83,139
user1539207
Author by

user1539207

Updated on February 23, 2020

Comments

  • user1539207
    user1539207 about 4 years

    Crashes on:

    <?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'); 
    ?>
    

    PHP Fatal error: Call to a member function format() on boolean

    But with other dates works well:

    <?php 
        $date = "10.06.2015 09:25:52";
        echo Datetime::createFromFormat('d-m-Y h:i:s',  $date)->format('Y-m-d h:i:s');
    ?>
    

    Wrong format?