標籤:style blog http io ar color sp on div
實現方法
function isDate( $dateString ) { return strtotime( date(‘Y-m-d‘, strtotime($dateString)) ) === strtotime( $dateString );} echo $this->isDate(‘2014-11-19‘) ? ‘true‘ : ‘false‘;echo ‘</br>‘;echo $this->isDate(‘2014-11-32‘)? ‘true‘ : ‘false‘;echo ‘</br>‘;echo $this->isDate(‘2014-a-b‘)? ‘true‘ : ‘false‘;echo ‘</br>‘;echo $this->isDate(‘2014-1-1‘)? ‘true‘ : ‘false‘;echo ‘</br>‘;echo $this->isDate(‘2014-01-01‘)? ‘true‘ : ‘false‘;/*結果truefalsefalsetruetrue*/
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時間戳記, 再進行比較。
原文地址:http://chhblog.com/article/294.html
php判斷日期格式是否合法