I'm new to regex and I'm having problem understanding how to formulate a pattern to a date for example (August 9, 2011)
Asked
Active
Viewed 57 times
-1
-
1Don't use a regex, use php's `strtotime` or `DateTime`. – Björn Tantau Sep 04 '17 at 12:31
-
@BjörnTantau Used DateTime and it worked pretty well. Thanks! – Steven Sep 04 '17 at 13:04
1 Answers
1
Regex is not best suited for date validation. Use PHP's built-in function to do so.
You can do it this way:
function validateDate($date, $format = 'Y-m-d H:i:s')
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
function was copied from this answer or php.net
Use it this way:
var_dump(validateDate('August 9, 2011', 'F j, Y')); # true
You can pass various date format as follows:
var_dump(validateDate('2012-02-28', 'Y-m-d')); # true
var_dump(validateDate('28/02/2012', 'd/m/Y')); # true
var_dump(validateDate('30/02/2012', 'd/m/Y')); # false
var_dump(validateDate('14:50', 'H:i')); # true
var_dump(validateDate('14:77', 'H:i')); # false