PHP date_get_last_errors() 函式



定義和用法

date_get_last_errors()DateTime::getLastErrors()::__construct() 的別名。此函式用於獲取解析日期字串時發生的警告和錯誤。

語法

date_get_last_errors();

引數

此函式不接受任何引數。

返回值

PHP date_get_last_errors() 函式返回一個數組,其中包含嘗試解析日期字串時發生的全部警告和錯誤。

PHP 版本

此函式首次引入於 PHP 5.5.0 版本,並在所有後續版本中均有效。

示例

以下示例演示了 date_get_last_errors() 函式的用法:

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

)

示例

使用此函式,您可以捕獲建立日期時發生的錯誤,如下所示:

<?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() 函式建立 DateTime 物件時發生的錯誤/警告:

//Creating a DateTime object
$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.
        )

)
php_function_reference.htm
廣告