Using the DateTime class to confirm successful conversion is good practice, but by itself allows for some text strings that would not visually represent a valid DateTime to be successfully converted to a DateTime object.
For example, simply passing in a single letter would not throw an exception, and would return a valid DateTime. For this reason I would recommend pairing the DateTime validation with a regex comparison(s) to ensure that at least the basic expected patterns of a Date/DateTime are present in the string as well. This is especially true if you are working with data from external sources and can't know with certainty what data will be populated, i.e. pulling records from a 3rd party API or database.
// eg: new DateTime('A') produces a valid DateTime object.
function is_datetime($string){
/*
* Adjust RegExp to handle various date formats that you may be expecting
* eg: /[\d]{4,}-[\d]{2,}-[\d]{2,}/ - matches date like 1970-01-01
* eg: /[\d]{2,}:[\d]{2,}:[\d]{2,}/ - matches time like 12:00:00
* combine like (!preg_match($eg1, $string) && !preg_match($eg2, $string))
* for wider coverage/variability in date/time string inputs
*/
if(!preg_match('/[\d]{4,}-[\d]{2,}-[\d]{2,}(.*)[\d]{2,}:[\d]{2,}:[\d]{2,}/', $string))
return false;
try{
new DateTime($string);
return true;
}catch (Exception $e){
return false;
}
}