date_get_last_errors()函數(shù)獲取警告和錯誤信息
date_get_last_errors()是DateTime::getLastErrors()::__ construct()的別名。 此函數(shù)用于獲取在分析日期字符串時出現(xiàn)的警告和錯誤。
date_get_last_errors();
此函數(shù)不接受任何參數(shù)
PHP date_get_last_errors()函數(shù)返回一個數(shù)組,其中包含您嘗試解析日期字符串時發(fā)生的所有警告和錯誤。
此函數(shù)最初是在PHP版本5.5.0中引入的,并且可以在所有更高版本中使用。
以下示例演示了date_get_last_errors()函數(shù)的用法-
<?php date_create("215-7896-848"); $errors = date_get_last_errors(); print_r($errors); ?>測試看看?/?
輸出結果
Array ( [warning_count] => 1 [warnings] => Array ( [8] => Double timezone specification ) [error_count] => 5 [errors] => Array ( [0] => Unexpected character [1] => Unexpected character [2] => Unexpected character [6] => Unexpected character [7] => Unexpected character ) )
使用此函數(shù),您可以捕獲創(chuàng)建日期時發(fā)生的錯誤,如下所示-
<?php try { $res = new DateTime("215-7896-848"); print($res); } catch (Exception $e) { print_r(DateTime::getLastErrors()); } ?>測試看看?/?
輸出結果
Array ( [warning_count] => 1 [warnings] => Array ( [8] => Double timezone specification ) [error_count] => 5 [errors] => Array ( [0] => Unexpected character [1] => Unexpected character [2] => Unexpected character [6] => Unexpected character [7] => Unexpected character ) )
以下示例顯示使用date_create_from_format()函數(shù)創(chuàng)建DateTime對象時發(fā)生的錯誤/警告-
//創(chuàng)建一個DateTime對象 $date = "25-Mar-1989"; $format = "d-Z-Y"; $res = date_create_from_format($format, $date); print_r(date_get_last_errors());測試看看?/?
輸出結果
Array ( [warning_count] => 0 [warnings] => Array ( ) [error_count] => 3 [errors] => Array ( [3] => The format separator does not match [4] => Unexpected data found. ) )