php根據年月獲取當月天數。


function get_day( $date )   
{
        $tem = explode('-' , $date);       //切割日期  得到年份和月份
        $year = $tem['0'];
        $month = $tem['1'];
        if( in_array($month , array( 1 , 3 , 5 , 7 , 8 , 01 , 03 , 05 , 07 , 08 , 10 , 12)))
        {
            // $text = $year.'年的'.$month.'月有31天';
            $text = '31';
        }
        elseif( $month == 2 )
        {
            if ( $year%400 == 0  || ($year%4 == 0 && $year%100 !== 0) )        //判斷是否是閏年
            {
                // $text = $year.'年的'.$month.'月有29天';
                $text = '29';
            }
            else{
                // $text = $year.'年的'.$month.'月有28天';
                $text = '28';
            }
        }
        else{

            // $text = $year.'年的'.$month.'月有30天';
            $text = '30';
        }
        return $text;
}

echo get_day('2016-8-1');

改造,返回日期數組

    /**
     * 獲取當月天數
     * @param  $date 
     * @param  $rtype  1天數 2具體日期數組
     * @return 
     */
    function get_day( $date ,$rtype = '1')   
    {
        $tem = explode('-' , $date);       //切割日期  得到年份和月份
        $year = $tem['0'];
        $month = $tem['1'];
        if( in_array($month , array( 1 , 3 , 5 , 7 , 8 , 01 , 03 , 05 , 07 , 08 , 10 , 12)))
        {
            // $text = $year.'年的'.$month.'月有31天';
            $text = '31';
        }
        elseif( $month == 2 )
        {
            if ( $year%400 == 0  || ($year%4 == 0 && $year%100 !== 0) )        //判斷是否是閏年
            {
                // $text = $year.'年的'.$month.'月有29天';
                $text = '29';
            }
            else{
                // $text = $year.'年的'.$month.'月有28天';
                $text = '28';
            }
        }
        else{

            // $text = $year.'年的'.$month.'月有30天';
            $text = '30';
        }

        if ($rtype == '2') {
            for ($i = 1; $i <= $text ; $i ++ ) {
                $r[] = $year."-".$month."-".$i;
            }
        } else {
            $r = $text;
        }
        return $r;
    }

    var_dump(get_day('2016-8-1','2'));


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM