How to find the last day of the month from date?

后端 未结 28 1775
孤城傲影
孤城傲影 2020-11-22 08:56

How can I get the last day of the month in PHP?

Given:

$a_date = \"2009-11-23\"

I want 2009-11-30; and given

$a_dat         


        
28条回答
  •  醉梦人生
    2020-11-22 09:22

    You can use "t" in date function to get the number of day in a particular month.

    The code will be something like this:

    function lastDateOfMonth($Month, $Year=-1) {
        if ($Year < 0) $Year = 0+date("Y");
        $aMonth         = mktime(0, 0, 0, $Month, 1, $Year);
        $NumOfDay       = 0+date("t", $aMonth);
        $LastDayOfMonth = mktime(0, 0, 0, $Month, $NumOfDay, $Year);
        return $LastDayOfMonth;
    }
    
    for($Month = 1; $Month <= 12; $Month++)
        echo date("Y-n-j", lastDateOfMonth($Month))."\n";
    

    The code is self-explained. So hope it helps.

提交回复
热议问题