如何确保日期采用以下格式:MM-DD-YY包括短划线

时间:2012-07-03 21:48:01

标签: php javascript regex

我想验证这种格式的日期:MM-DD-YY(包括破折号)。我如何在PHP(或JavaScript)中执行此操作?

3 个答案:

答案 0 :(得分: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'));

答案 1 :(得分: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

答案 2 :(得分: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