Check if a string is a valid datetime in PHP
Here is a function in PHP to check if a string represents a valid datetime. This approach was suggested by glavic on the official PHP website.
Source Code
/**
* Checks if a given string is a valid datetime.
* @param string $str The datetime string to validate.
* @param string $format The datetime format to use for validation.
* @return bool Returns true if the string matches the specified format and is valid, otherwise false.
*/
function validateDateTimeFormat($str, $format = 'Y-m-d H:i:s')
{
$d = DateTime::createFromFormat($format, $str);
return $d && $d->format($format) == $str;
}
Validation
Provide a datetime string and a format, then execute the function. If no format is specified, the default "Y-m-d H:i:s" format is used for validation.