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

考虑到:

$a_date = "2009-11-23"

我想要2009-11-30;鉴于

$a_date = "2009-12-23"

我要2009-12-31。


当前回答

另一种使用mktime而不是date('t')的方法:

$dateStart= date("Y-m-d", mktime(0, 0, 0, 10, 1, 2016)); //2016-10-01
$dateEnd = date("Y-m-d", mktime(0, 0, 0, 11, 0, 2016)); //This will return the last day of october, 2016-10-31 :)

所以用这种方法,它会计算它是31 30还是29

其他回答

这是一个更优雅的表达月底的方式:

  $thedate = Date('m/d/Y'); 
  $lastDayOfMOnth = date('d', mktime(0,0,0, date('m', strtotime($thedate))+1, 0, date('Y', strtotime($thedate)))); 

还有一个内置的PHP函数cal_days_in_month()?

"此函数将返回指定日历的某月中的天数。" http://php.net/manual/en/function.cal-days-in-month。

echo cal_days_in_month(CAL_GREGORIAN, 11, 2009); 
// = 30

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

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

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

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

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

使用Zend_Date非常简单:

$date->setDay($date->get(Zend_Date::MONTH_DAYS));