我想验证日期是否采用以下格式:MM-DD-YY(包括破折号)。我如何在 PHP(或 JavaScript)中做到这一点?
问问题
136 次
3 回答
0
function validate_date($string) {
$date = DateTime::createFromFormat('m-j-y', $string);
if ($date === false) {
return false;
}
$dateparts = explode('-', $string);
if (!checkdate($dateparts[0], $dateparts[1], $dateparts[2])) {
return false;
}
return true; // You can also make this return $date if you want to use it further
}
var_dump(validate_date('02-28-99')); // true
var_dump(validate_date('02-29-99')); // false
于 2012-07-03T22:37:21.003 回答
0
JS
function isValidDate(date)
{
var matches = /^(\d{2})[-\/](\d{2})[-\/](\d{2})$/.exec(date);
if (matches == null) return false;
var d = matches[2];
var m = matches[1] - 1;
var y = matches[3];
var composedDate = new Date(y, m, d);
return composedDate.getDate() == d &&
composedDate.getMonth() == m &&
composedDate.getFullYear() == y;
}
console.log(isValidDate('10-12-61'));
console.log(isValidDate('12/11/61'));
于 2012-07-03T21:51:36.500 回答
0
代码:
$d = "02-05-20";
if(strlen($d) == 8 && checkdate($d[0].$d[1],$d[3].$d[4],$d[6].$d[7]))
{
echo "Valid Date";
}
检查字符串格式是否正确以及日期本身是否有效。
02-05-20
验证true
13-05-20
验证false
(没有第十三个月)2-5-20
验证false
于 2012-07-03T21:54:29.377 回答