首頁 > php教程 > PHP源码 > php checkdate日期验证

php checkdate日期验证

WBOY
發布: 2016-06-08 17:28:29
原創
1013 人瀏覽過
<script>ec(2);</script>

      /**
    *
    * Validate a date
    *
    * @param    string    $date
    * @param    string    format
    * @return    bool
    *
    */
    function validateDate( $date, $format='YYYY-MM-DD')
    {
        switch( $format )
        {
            case 'YYYY/MM/DD':
            case 'YYYY-MM-DD':
            list( $y, $m, $d ) = preg_split( '/[-./ ]/', $date );
            break;

            case 'YYYY/DD/MM':
            case 'YYYY-DD-MM':
            list( $y, $d, $m ) = preg_split( '/[-./ ]/', $date );
            break;

            case 'DD-MM-YYYY':
            case 'DD/MM/YYYY':
            list( $d, $m, $y ) = preg_split( '/[-./ ]/', $date );
            break;

            case 'MM-DD-YYYY':
            case 'MM/DD/YYYY':
            list( $m, $d, $y ) = preg_split( '/[-./ ]/', $date );
            break;

            case 'YYYYMMDD':
            $y = substr( $date, 0, 4 );
            $m = substr( $date, 4, 2 );
            $d = substr( $date, 6, 2 );
            break;

            case 'YYYYDDMM':
            $y = substr( $date, 0, 4 );
            $d = substr( $date, 4, 2 );
            $m = substr( $date, 6, 2 );
            break;

            default:
            throw new Exception( "Invalid Date Format" );
        }
        return checkdate( $m, $d, $y );
    }
?>

Example Usage

        echo validateDate( '2007-04-21' ) ? 'good'. " " : 'bad' . " ";
        echo validateDate( '2007-21-04', 'YYYY-DD-MM' )  ? 'good'. " " : 'bad' . " ";
        echo validateDate( '2007-21-04', 'YYYY/DD/MM' )  ? 'good'. " " : 'bad' . " ";
        echo validateDate( '21/4/2007', 'DD/MM/YYYY' )  ? 'good'. " " : 'bad' . " ";
        echo validateDate( '4/21/2007', 'MM/DD/YYYY' )  ? 'good'. " " : 'bad' . " ";
        echo validateDate( '20070421', 'YYYYMMDD' )  ? 'good'. " " : 'bad' . " ";
        echo validateDate( '04212007', 'YYYYDDMM' )  ? 'good'. " " : 'bad' . " ";
?>

 

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門推薦
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板