php判斷日期格式是否合法

來源:互聯網
上載者:User

標籤: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判斷日期格式是否合法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.