$date = date_create('Wrong date');
print_r(DateTime::getLastErrors());
Output is here
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 )
)
Object oriented
try {
$date = new DateTime('Wrong date');
} catch (Exception $e) {
print_r(DateTime::getLastErrors());
}
$date = DateTime::createFromFormat('d/m/Y', '01/13/2019');
// change above input date for different messages. //
$errors = DateTime::getLastErrors();
if (!empty($errors['warning_count'])) {
echo "Strictly speaking, input date is invalid! ( Warning ) ";
}
if (!empty($errors['error_count'])) {
echo "input date is invalid! ( error ) ";
}
//echo "<br>Input date is : ".$date->format('Y-m-d H:i:s');
$date = DateTime::createFromFormat('d/m/Y', '01/13/2019');
Strictly speaking, input date is invalid! ( Warning )
Input date is : 2020-01-01 12:34:34
$date = DateTime::createFromFormat('d/m/Y', 'Wrong data');
input date is invalid! ( error )
$date = DateTime::createFromFormat('Y-m-d', '2023-13-01');
$errors = DateTime::getLastErrors();
//print_r($errors);
if ($errors['warning_count'] > 0) {
print_r($errors['warnings']); // Output: Array of errors
}
Output
Array ( [10] => The parsed date was invalid )
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.