如何在PHP中获得每月的最后一天?

考虑到:

$a_date = "2009-11-23"

我想要2009-11-30;鉴于

$a_date = "2009-12-23"

我要2009-12-31。


当前回答

如果你知道一个月的最后一天,

public function getLastDateOfMonth($month)
    {
        $date = date('Y').'-'.$month.'-01';  //make date of month 
        return date('t', strtotime($date)); 
    }

$this->getLastDateOfMonth(01); //31

其他回答

有很多方法可以得到一个月的最后一天。

//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]); 

2行代码,你就完成了:

$oDate = new DateTime("2019-11-23");

// now your date object has been updated with last day of month    
$oDate->setDate($oDate->format("Y"),$oDate->format("m"),$oDate->format("t"));

// or to just echo you can skip the above line using this
echo $oDate->format("Y-m-t");

碳API扩展PHP DateTime

Carbon::parse("2009-11-23")->lastOfMonth()->day;

or

Carbon::createFromDate(2009, 11, 23)->lastOfMonth()->day;

将返回

30

现在,如果你有月份和年份,DateTime可以很方便地做到这一点

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

来自另一个DateTime对象

$date = new DateTime('last day of '.$otherdate->format('Y-m'));

T返回给定日期当月的天数(date参见文档):

$a_date = "2009-11-23";
echo date("Y-m-t", strtotime($a_date));