提供幾個方案:
優點:
缺點:
public function validateDate(string $date)
{
return (bool)preg_match(
"/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",
$date
);
}
優點:
/**
*
* Validate if input string is valid DATE format
*
* @param string $date Such as "2020-12-12"
* @param string $format Validation rule will depands on this
* @return boolean If date format valid, return true
*
*/
public function validateDate(string $date, string $format = 'Y-m-d')
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
優點:
public function validateDate(string $date, string $format = 'Y-m-d')
{
return date($format, strtotime($date)) == $date;
}