PHP Conference Japan 2024

DateTimeImmutable::getLastErrors

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

DateTimeImmutable::getLastErrors返回警告和錯誤

描述

public static DateTimeImmutable::getLastErrors(): 陣列|false

返回在解析日期/時間字串時發現的警告和錯誤的陣列。

參數

此函式沒有參數。

返回值

返回包含警告和錯誤資訊的陣列,如果沒有警告或錯誤,則返回 false

更新日誌

版本 描述
8.2.0 在 PHP 8.2.0 之前,當沒有警告或錯誤時,此函式不會返回 false。相反,它總是返回文件中規定的陣列結構。

範例

範例 #1 DateTimeImmutable::getLastErrors() 範例

<?php
try {
$date = new DateTimeImmutable('asdfasdf');
} catch (
Exception $e) {
// 僅供示範...
print_r(DateTimeImmutable::getLastErrors());

// 真正物件導向的做法是
// echo $e->getMessage();
}
?>

以上範例將輸出

Array
(
   [warning_count] => 1
   [warnings] => Array
       (
           [6] => Double timezone specification
       )

   [error_count] => 1
   [errors] => Array
       (
           [0] => The timezone could not be found in the database
       )

)

範例輸出中的索引 6 和 0 指的是字串中發生錯誤的字元索引。

新增註釋

使用者貢獻的註釋 1 則註釋

_mittens
1 年前
如果您好奇內部陣列何時重置(來自 https://onlinephp.io/c/3ee35

<?php

$date0
= DateTimeImmutable::createFromFormat('!Y-m-d', '2020-31-31');
var_dump($date0->format('c')); // 2022-07-31T00:00:00+00:00

foreach(range(0,2) as $_)
// 內部錯誤不會重置
var_dump( join(DateTimeImmutable::getLastErrors()['warnings']) ); // 解析的日期無效

$date1 = DateTimeImmutable::createFromFormat('!Y-m-d', '2020-12-31');
var_dump($date1->format('c')); // 2020-12-31T00:00:00+00:00

// 內部錯誤已重置
var_dump( empty(DateTimeImmutable::getLastErrors()['warnings']) ); // true

$date2 = DateTimeImmutable::createFromFormat('!Y-m-d', '2020-31-31');
var_dump( join(DateTimeImmutable::getLastErrors()['warnings']) ); // 解析的日期無效
$date3 = new DateTimeImmutable('2023-12-31T00:00:00.000000Z');

// 內部錯誤已重置
var_dump( empty(DateTimeImmutable::getLastErrors()['warnings']) ); // true
?>

輸出
字串(25) "2022-07-31T00:00:00+00:00"
字串(27) "解析的日期無效"

字串(13) "The parsed date was invalid"
字串(27) "解析的日期無效"

字串(13) "The parsed date was invalid"
字串(27) "解析的日期無效"

字串(13) "The parsed date was invalid"
字串(25) "2020-12-31T00:00:00+00:00"
布林(true)
字串(27) "解析的日期無效"

字串(13) "The parsed date was invalid"
布林(true)

To Top