I have written a PHP function to check a supplied string is a valid date or not. Lets have a look into the code.
/**
* The function is_date() validates the date and returns true or false
* @param $str sting expected valid date format
* @return bool returns true if the supplied parameter is a valid date
* otherwise false
*/
function is_date( $str ) {
try {
$dt = new DateTime( trim($str) );
}
catch( Exception $e ) {
return false;
}
$month = $dt->format('m');
$day = $dt->format('d');
$year = $dt->format('Y');
if( checkdate($month, $day, $year) ) {
return true;
}
else {
return false;
}
}
Let’s use and improve the function.
Leave a Reply