在以下程式碼中
$t = microtime(true);
$now = DateTime::createFromFormat('U.u', $t);
$now = $now->format("H:i:s.v");
如果 microtime(true) 剛好返回一個小數點後全為零的浮點數,則嘗試 format() 將會返回一個致命錯誤。這是因為 DateTime::createFromFormat('U.u', $aFloatWithAllZeros) 會返回 false。
解決方法 (while 迴圈是用於測試解決方案是否有效)
$t = microtime(true);
$now = DateTime::createFromFormat('U.u', $t);
while (!is_bool($now)) {//用於測試解決方案}
$t = microtime(true);
$now = DateTime::createFromFormat('U.u', $t);
}
if (is_bool($now)) {//問題所在}
$now = DateTime::createFromFormat('U', $t);//解決方案}
}
$now = $now->format("H:i:s.v");