The getLastErrors Method of the DateTime Class
The getLastErrors
method returns an array with information about the last errors and warnings
that occurred when creating or working with DateTime
objects. This is useful for debugging
and handling invalid dates.
Syntax
DateTime::getLastErrors();
Example
Let's try to create a DateTime object with an invalid date and look at the returned errors:
<?php
$date = DateTime::createFromFormat('Y-m-d', '2023-02-30');
$res = DateTime::getLastErrors();
print_r($res);
?>
Code execution result:
[
'warning_count' => 1,
'warnings' => [6 => 'The parsed date was invalid'],
'error_count' => 0,
'errors' => []
]
Example
Let's try to create a DateTime object with a completely invalid date format:
<?php
$date = DateTime::createFromFormat('Y-m-d', 'invalid-date');
$res = DateTime::getLastErrors();
print_r($res);
?>
Code execution result:
[
'warning_count' => 0,
'warnings' => [],
'error_count' => 1,
'errors' => [0 => 'The parsed string was invalid']
]