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

后端 未结 28 1479
孤城傲影
孤城傲影 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:21

    Nowadays DateTime does this quite conveniently if you have month and year you can

    $date = new DateTime('last day of '.$year.'-'.$month);
    

    From another DateTime object that would be

    $date = new DateTime('last day of '.$otherdate->format('Y-m'));
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 09:23

    What is wrong - The most elegant for me is using DateTime

    I wonder I do not see DateTime::createFromFormat, one-liner

    $lastDay = \DateTime::createFromFormat("Y-m-d", "2009-11-23")->format("Y-m-t");
    
    0 讨论(0)
  • 2020-11-22 09:23

    There are ways to get last day of month.

    //to get last day of current month
    echo date("t", strtotime('now'));
    
    //to get last day from specific date
    $date = "2014-07-24";
    echo date("t", strtotime($date));
    
    //to get last day from specific date by calendar
    $date = "2014-07-24";
    $dateArr=explode('-',$date);
    echo cal_days_in_month(CAL_GREGORIAN, $dateArr[1], $dateArr[0]); 
    
    0 讨论(0)
提交回复
热议问题