Working with valid but invalid dates in PHP DateTime
I am trying to use PHP DateTime to validate dates, but DateTime will accept some well-formed but invalid dates, such as 2015-02-30
that will turn into March 2, 2015
without throwing an exception. Any suggestions on how to work around this using DateTime or some other method?
Edit: Thanks everyone for the help! I was handling errors by catching the exception, but I didn't realize that the exception was only thrown by an error, not a warning, and this kind of input only throws a warning.
source to share
Check for errors with DateTime::getLastErrors()
. Well-formed but invalid date:
$date = '2015-02-30';
DateTime::createFromFormat('Y-m-d', $date);
$errors = DateTime::getLastErrors();
print_r($errors);
Productivity:
Array
(
[warning_count] => 1
[warnings] => Array
(
[10] => The parsed date was invalid
)
[error_count] => 0
[errors] => Array
(
)
)
Whereas an unformatted date $date = '02-30';
gives:
Array
(
[warning_count] => 0
[warnings] => Array
(
)
[error_count] => 1
[errors] => Array
(
[5] => Data missing
)
)
source to share
You can use checkdate()
to check if a date is valid before using DateTime()
:
$parts = explode('-', '2015-02-30');
if (checkdate($parts[1], $parts[2], $parts[0])) {
// DateTime() stuff here
}
source to share