date_get_last_errors()

This function returns array with elements about warnings and errors.
$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());
}

Showing error

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

Example: Validating Date Input

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

PHP Date Functions Adding Date by using DateInterval


Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer