天天看點

php判斷字元串是否是日期類型,php判斷日期格式是否合法

實作方法

function isDate( $dateString) {return strtotime( date(‘Y-m-d‘, strtotime($dateString)) ) === strtotime( $dateString);

}echo $this->isDate(‘2014-11-19‘) ? ‘true‘ : ‘false‘;echo ‘‘;echo $this->isDate(‘2014-11-32‘)? ‘true‘ : ‘false‘;echo ‘‘;echo $this->isDate(‘2014-a-b‘)? ‘true‘ : ‘false‘;echo ‘‘;echo $this->isDate(‘2014-1-1‘)? ‘true‘ : ‘false‘;echo ‘‘;echo $this->isDate(‘2014-01-01‘)? ‘true‘ : ‘false‘;

date(‘Y-m-d‘, strtotime($dateString))  這段代碼是将輸入的時間字元串轉換成unix時間戳(自1970-1-1 0:0:0起),然後再轉回日期字元串。 如果輸入的日期字元串格式不正确, 那麼轉換前的值與轉換後的值是不一緻的, 也就是說 date(‘Y-m-d‘, strtotime($dateString)) == $dateString 這句代碼的結果将false。那為什麼還要将上面的代碼寫成 strtotime( date(‘Y-m-d‘, strtotime($dateString)) ) === strtotime( $dateString ) 這樣呢?因為将代碼寫成date(‘Y-m-d‘, strtotime($dateString)) == $dateString這樣, 那麼如果$dateString的值為2014-1-1這種格式( 一個合法的時間字元串),傳回的結果也将為false, 因為date(‘Y-m-d‘,strtotime(‘2014-1-1‘))傳回的結果為2014-01-01這個樣子, 如果月份和日期為個位數, 會在前面自動補上0,從字元串比較的層面看2014-1-1很明顯不等于2014-01-01, 是以需要在外層加上strtotime, 将兩邊的日期都轉換成unix時間戳, 再進行比較。