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

考虑到:

$a_date = "2009-11-23"

我想要2009-11-30;鉴于

$a_date = "2009-12-23"

我要2009-12-31。


当前回答

如果你使用碳API扩展PHP DateTime,你可以得到一个月的最后一天:

$date = Carbon::now();
$date->addMonth();
$date->day = 0;
echo $date->toDateString(); // use toDateTimeString() to get date and time 

其他回答

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

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

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

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

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

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

来自另一个DateTime对象

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

使用Zend_Date非常简单:

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

你的解决方案在这里。

$lastday = date('t',strtotime('today'));