What would the regex
expression that would go into preg_split
function to validate date in the format of
7-Mar-10
or how开发者_StackOverflow社区 can I validate a date of format 7-Mar-10
in PHP
Thanks.
strtotime
?
And here's an example of how to use it
function isValidTime($str) {
return strtotime($str) !== false;
}
The DateTime class's createFromFormat method (also available in function form) allows one to parse a date string against a given format. The class also has the benefit of keeping track of errors for you should you want see what went wrong.
Here's a quick yay/nay validation function:
function valid($date, $format = 'j-M-y') {
$datetime = DateTime::createFromFormat($format, $date, new DateTimeZone('UTC'));
$errors = DateTime::getLastErrors();
return ($errors['warning_count'] + $errors['error_count'] === 0);
}
var_dump(valid('7-Mar-10')); // bool(true)
var_dump(valid('7-3-10')); // bool(false)
Of course, the above is only for validating a single format of date (and only available as of PHP 5.3) so if you are just wanting to accept any date (even 'wrong' dates that get automatically converted to the right value), or for whatever reason cannot yet use PHP 5.3, then as mentioned in other answers, strtotime would be of assistance.
I'd make it first with explode,
$parts=explode("-",$date);
then with array
$months=array("Jan"=>1,"Feb"=>2...)
and then use checkdate($months[$parts1],$parts[0],$parts[2]);
精彩评论