如何在PHP中获得每月的最后一天?
考虑到:
$a_date = "2009-11-23"
我想要2009-11-30;鉴于
$a_date = "2009-12-23"
我要2009-12-31。
如何在PHP中获得每月的最后一天?
考虑到:
$a_date = "2009-11-23"
我想要2009-11-30;鉴于
$a_date = "2009-12-23"
我要2009-12-31。
当前回答
试试这个,如果你使用的是PHP 5.3+,
$a_date = "2009-11-23";
$date = new DateTime($a_date);
$date->modify('last day of this month');
echo $date->format('Y-m-d');
为了查找下个月最后的日期,修改如下:
$date->modify('last day of 1 month');
echo $date->format('Y-m-d');
等等。
其他回答
我在这里将它包装在我的日期时间助手类中 https://github.com/normandqq/Date-Time-Helper 使用 $dateLastDay = Model_DTHpr::getLastDayOfTheMonth();
完成了
这是一个完整的函数:
public function get_number_of_days_in_month($month, $year) {
// Using first day of the month, it doesn't really matter
$date = $year."-".$month."-1";
return date("t", strtotime($date));
}
这将输出如下:
echo get_number_of_days_in_month(2,2014);
输出:28
我需要下个月的最后一天,也许有人会需要它:
echo date("Y-m-t", strtotime("next month")); //is 2020-08-13, return 2020-09-30
还有一个内置的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
你的解决方案在这里。
$lastday = date('t',strtotime('today'));