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

考虑到:

$a_date = "2009-11-23"

我想要2009-11-30;鉴于

$a_date = "2009-12-23"

我要2009-12-31。


当前回答

现在,如果你有月份和年份,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));

我知道这有点晚了,但我认为有一种更优雅的方式来使用PHP 5.3+使用DateTime类:

$date = new DateTime('now');
$date->modify('last day of this month');
echo $date->format('Y-m-d');

这应该可以工作:

$week_start = strtotime('last Sunday', time());
$week_end = strtotime('next Sunday', time());

$month_start = strtotime('first day of this month', time());
$month_end = strtotime('last day of this month', time());

$year_start = strtotime('first day of January', time());
$year_end = strtotime('last day of December', time());

echo date('D, M jS Y', $week_start).'<br/>';
echo date('D, M jS Y', $week_end).'<br/>';

echo date('D, M jS Y', $month_start).'<br/>';
echo date('D, M jS Y', $month_end).'<br/>';

echo date('D, M jS Y', $year_start).'<br/>';
echo date('D, M jS Y', $year_end).'<br/>';

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");

你可以为下个月的第一天创建一个日期,然后使用strtotime("-1 day", $firstOfNextMonth)