2013-03-11 25 views
0

我想使用preg_match()和checkdate()函數驗證日期時間格式。 我的格式是「dd/MM/yyyy hh:mm:ss」。 我的代碼有什麼問題?PHP使用preg_match和checkdate錯誤結果檢查日期時間格式

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 
+0

'12-21-2000'在您的定義中代表「2000年,21個月,12天」,這當然是虛假的... – Passerby 2013-03-11 05:01:20

回答

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,或者你在正則表達式中解析錯誤。

+0

「$ mm不能是21」哈哈 謝謝David Kiger – PoundXI 2013-03-11 05:16:07