0

我想使用 preg_match() 和 checkdate() 函数验证日期时间格式。我的格式是“dd/MM/yyyy hh:mm:ss”。我的代码有什么问题?

function checkDatetime($dateTime){
    $matches = array();
    if(preg_match("/^(\d{2})-(\d{2})-(\d{4}) ([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/", $dateTime, $matches)){
        print_r($matches); echo "<br>";
        $dd = trim($matches[1]);
        $mm = trim($matches[2]);
        $yy = trim($matches[3]);
        return checkdate($mm, $dd, $yy); // <- Problem here?
    }else{
        echo "wrong format<br>";
        return false;
    }    
} 

//wrong result
if(checkDatetime("12-21-2000 03:04:00")){
    echo "checkDatetime true<br>";
}else{
    echo "checkDatetime false<br>";
}

//correct result
if(checkdate("12", "21", "2000")){
    echo "checkdate true<br>";
}else{
    echo "checkdate false<br>";
}

输出:

Array ( [0] => 12-21-2000 03:04:00 [1] => 12 [2] => 21 [3] => 2000 [4] => 03 [5] => 04 [6] => 00 )

checkDatetime false

checkdate true
4

1 回答 1

3

if(checkDatetime("12-21-2000 03:04:00"))导致

$dd = 12
$mm = 21
$yy = 2000

然后调用return checkdate($mm, $dd, $yy);,相当于return checkdate(21, 12, 2000);

很明显$mm不能是 21,但我不能说你是否传递了错误的格式,checkDatetime或者你是否在正则表达式中解析错误。

于 2013-03-11T05:10:11.197 回答