天天看點

php中的時間格式校驗函數

如何校驗使用者輸入的時間是否是合要求的?其實很簡單:

/** 

 * 判斷時間格式是否正确 

 * 

 * @param string $param 輸入的時間 

 * @param string $format 指定的時間格式 

 * @return boolean 

 */ 

function isDatetime($param = '', $format = 'Y-m-d H:i:s') 

    return date($format, strtotime($param)) === $param; 

echo "<pre>"; 

$str = "2012-02-30 12:31:22"; 

echo $str." - "; 

echo isDatetime($str) ? "TRUE" : "FALSE"; 

echo "\n"; 

$str = "2012-02-10 12:31:22"; 

$str = "2012-02-10"; 

echo isDatetime($str, "Ymd") ? "TRUE" : "FALSE"; 

echo isDatetime($str, "Y-m-d") ? "TRUE" : "FALSE"; 

輸出結果:

2012-02-30 12:31:22 - FALSE 

2012-02-10 12:31:22 - TRUE 

2012-02-10 - FALSE 

2012-02-10 - TRUE 

用到的技巧很簡單,就是将傳入的時間用strtotime轉成時間戳,再用date函數轉成指定的格式,如果轉換後的字元串與傳入的相同,那就說明格式是正确的,so easy.

本文轉自 ustb80 51CTO部落格,原文連結:http://blog.51cto.com/ustb80/1036228,如需轉載請自行聯系原作者