I would like to check for a valid date in ‘mm/dd/yyyy’ format. When I call the function below with isValidDateTime('12/10/2012'), it returns false. Could you please let me know what could be wrong?
function isValidDateTime($dateTime)
{
if (preg_match("/^(\d{2})/(\d{2})/(\d{4}) ([0-5][0-9]):([0-5][0-9]):([01][0-9]|2[0-3])$/", $dateTime, $matches)) {
if (checkdate($matches[1], $matches[3], $matches[2])) {
return true;
}
}
return false;
}
Here is a simpler way to accomplish your date validation … it doesn’t verify the mm/dd/yyyy format, but it doesn’t need to.
The
DateTimeconstructor throws an exception if passed an invalid date string. Once you have a valid date, you can useDateTime::format()to output the date in any format you want.