2015-06-10 17 views
8

si blocca su:PHP Fatal error: Call to un formato funzione membro() su booleani

<?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

Ma con altre date funziona bene:

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

formato sbagliato?

+0

Nessuno dei due funziona effettivamente –

+0

$ date = "10.06.2015 09:25:52"; echo Datetime :: createFromFormat ('d-m-Y h: i: s', $ date) -> formato ('Y-m-d h: i: s'); -works – user1539207

+0

$ date = "13-06-2015 23:45:52"; echo Datetime :: createFromFormat ('d-m-Y h: i: s', $ date) -> formato ('Y-m-d h: i: s'); - non funziona comunque – user1539207

risposta

12

Né esempio il lavoro quando si dispone di più errori:

  1. hai dimenticato il tuo secondo parametro per Datetime::createFromFormat()
  2. h:i:s dovrebbe essere H:i:s
  3. vostra data nel secondo esempio è separato da un non . un -

Correzioni:

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

2. 'h: i: s' dovrebbe essere' H: i: s' - che ha risolto il mio problema, 'h' - formato 12 ore. Grazie – user1539207

+0

Inoltre, questo è 'DateTime' e non' Datetime' – TwystO

3

Nel mio caso mi è stato sempre questo errore perché stavo usando microtime(true) come input:

$now = DateTime::createFromFormat('U.u', microtime(true)); 

Nei momenti specifici in cui microtime restituisce un float con solo zeri come decimali, questo errore è comparso.

Così ho dovuto verificare se i suoi decimali e aggiungere una parte decimale:

$aux = microtime(true); 
$decimais = $aux - floor($aux); 
if($decimais<=10e-5) $aux += 0.1; 
$now = DateTime::createFromFormat('U.u', $aux); 

EDIT:

Grazie alla precisione in virgola mobile a volte piano porta un piano incorret, così ho dovuto usare un approccio più diretto:

$aux = microtime(true); 
$now = DateTime::createFromFormat('U.u', $aux);   
if (is_bool($now)) $now = DateTime::createFromFormat('U.u', $aux += 0.001); 
+1

oppure potresti controllare se non è un decimale e usare 'U' – malhal

Problemi correlati