这不是一个完整的日期检查,因为可以构建无效日期,但可能足以满足您的目的(并且当没有值大于 12 时,无法检测日期和月份的位置,反之亦然 -在我的代码中,当没有值大于 19 时也是如此)。我只是将所有格式转换为 iso 日期,因为它有利于排序或与 mysql 一起使用:
$dates = array();
$dates[] = "18-11-1991";
$dates[] = "1991-11-18";
$dates[] = "18/11/1991";
$dates[] = "1991/11/18";
$dates[] = "1991 11 18";
foreach($dates as $date) {
$iso_date = "";
if(preg_match("/^([0-3][0-9])-([0-1][0-9])-([0-9]{4})\$/",$date,$reg)) {
$iso_date = $reg[3]."-".$reg[2]."-".$reg[1];
} elseif(preg_match("/^([0-9]{4})-([0-1][0-9])-([0-3][0-9])\$/",$date,$reg)) {
$iso_date = $date;
} elseif(preg_match("/^([0-3][0-9])\/([0-1][0-9])\/([0-9]{4})\$/",$date,$reg)) {
$iso_date = $reg[3]."-".$reg[2]."-".$reg[1];
} elseif(preg_match("/^([0-9]{4})\/([0-1][0-9])\/([0-3][0-9])\$/",$date,$reg)) {
$iso_date = $reg[1]."-".$reg[2]."-".$reg[3];
}
if(empty($iso_date)) {
echo "<br>ERROR: date $date doesn't match one of the supported formats.";
} else {
echo "<br>$date = $iso_date";
}
}
这将输出:
18-11-1991 = 1991-11-18
1991-11-18 = 1991-11-18
18/11/1991 = 1991-11-18
1991/11/18 = 1991-11-18
ERROR: date 1991 11 18 doesn't match one of the supported formats.
编辑:如果您愿意,可以添加对 iso_date 的检查,如果它是有效日期:
$p = explode("-",$iso_date);
if(count($p)==3 and checkdate($p[1],$p[2],$p[1])) {
echo " (date is valid)";
}