<?php
$date1 = '2019-01-01';
$date2 = '2019-01-01 23:59';
$date3 = '2019-01-01 23:59:59';
$date4 = '2019-01';
function checkDateTime($date) {
$patten = "/^\d{4}[\-](0?[1-9]|1[012])[\-](0?[1-9]|[12][0-9]|3[01])(\s+(0?[0-9]|1[0-9]|2[0-3])\:(0?[0-9]|[1-5][0-9])(\:(0?[0-9]|[1-5][0-9]))?)?$/";
if (preg_match($patten, $date)) {
echo $date.' 通过验证'.PHP_EOL;
} else {
echo $date.' 日期非法'.PHP_EOL;
}
}
checkDateTime($date1);
checkDateTime($date2);
checkDateTime($date3);
checkDateTime($date4);
结果
2019-01-01 通过验证
2019-01-01 23:59 通过验证
2019-01-01 23:59:59 通过验证
2019-01 日期非法