Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 895
user1539207 Avatar asked Jun 10 '15 00:06

user1539207


3 Answers

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');
?>
like image 145
John Conde Avatar answered Oct 16 '22 23:10

John Conde


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);
like image 27
carla Avatar answered Oct 16 '22 23:10

carla


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

like image 3
Serge Kishiko Avatar answered Oct 16 '22 21:10

Serge Kishiko