in PHP, how to check if the date_create return an valid date object?
date_create('sd开发者_C百科fsdfdsfsd') //invalid
date_create('2010-07-30 08:03') //valid
As you can see from the documentation it is simply an alias of DateTime::__construct which:
Returns a new DateTime instance. Procedural style returns FALSE on failure.
Or you could validate first:
php check for a valid date, weird date conversions
If the date_create
function doesn't return a valid date object, it'll return FALSE
.
A much more complicated alternative is to validate its parameter with Regex according to http://www.php.net/manual/en/datetime.formats.php.
Isn't this covered right at the top of the manual page?
<?php
$date = date_create('2000-01-01');
if (!$date) {
$e = date_get_last_errors();
foreach ($e['errors'] as $error) {
echo "$error\n";
}
exit(1);
}
echo date_format($date, 'Y-m-d');
?>
精彩评论