PHP致命错误:在布尔值上调用成员函数format()

use*_*207 18 php datetime date-formatting

崩溃:

<?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'); 
?>
Run Code Online (Sandbox Code Playgroud)

PHP致命错误:在布尔值上调用成员函数format()

但其他日期效果很好:

<?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');
?>
Run Code Online (Sandbox Code Playgroud)

错误的格式?

Joh*_*nde 25

这两个示例都没有,因为您有多个错误:

  1. 你忘了你的第二个参数了 Datetime::createFromFormat()
  2. h:i:s 应该 H:i:s
  3. 第二个示例中的日期由a .而不是a 分隔-

修正:

<?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');
?>
Run Code Online (Sandbox Code Playgroud)


car*_*rla 6

在我的情况下,我收到此错误,因为我使用microtime(true)了输入:

$now = DateTime::createFromFormat('U.u', microtime(true));
Run Code Online (Sandbox Code Playgroud)

microtime返回仅以零作为小数的浮点数的特定时刻,出现此错误。

因此,我必须验证其小数点是否为小数并添加小数部分:

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

编辑

由于浮点精度,有时地板会带来不正确的地板,所以我不得不使用更直接的方法:

$aux =  microtime(true);
$now = DateTime::createFromFormat('U.u', $aux);        
if (is_bool($now)) $now = DateTime::createFromFormat('U.u', $aux += 0.001);
Run Code Online (Sandbox Code Playgroud)