Home  >  Article  >  Backend Development  >  php gets the number of days in a month

php gets the number of days in a month

(*-*)浩
(*-*)浩Original
2019-09-16 11:03:525945browse

Given a month, it is required to return how many days there are in this month.

php gets the number of days in a month

There are many ways. The first one uses the built-in function

cal_days_in_month:Return The number of days in a certain month in a certain year in a certain calendar (recommended learning: PHP Programming from Beginner to Mastery)

int cal_days_in_month ( int $calendar , int $month , int $year )

calendar: Calendar used for calculation

month: Select a certain month in the calendar

year: Select a certain year in the calendar

The cal_day_in_month function needs to be compiled with --enable-calendar before PHP can be used

The second type is a custom function that uses the year and month to determine how many days there are in a month.

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天';
    }
    elseif( $month == 2 )
    {
        if ( $year%400 == 0  || ($year%4 == 0 && $year%100 !== 0) )        //判断是否是闰年
        {
            $text = $year.'年的'.$month.'月有29天';
        }
        else{
            $text = $year.'年的'.$month.'月有28天';
        }
    }
    else{
        $text = $year.'年的'.$month.'月有30天';
    }
    return $text;
}

$i=2;
$y=2013;
echo get_day($y.'/'.$i);

The above is the detailed content of php gets the number of days in a month. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn