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

考虑到:

$a_date = "2009-11-23"

我想要2009-11-30;鉴于

$a_date = "2009-12-23"

我要2009-12-31。


当前回答

我迟到了,但有几个简单的方法可以做到这一点:

$days = date("t");
$days = cal_days_in_month(CAL_GREGORIAN, date('m'), date('Y'));
$days = date("j",mktime (date("H"),date("i"),date("s"),(date("n")+1),0,date("Y")));

使用mktime()是我去完全控制时间的各个方面… 即

echo "<br> ".date("Y-n-j",mktime (date("H"),date("i"),date("s"),(11+1),0,2009));

将日期设置为0,将月份向上移动1,就会得到上个月的最后一天。0和负数在不同的参数中具有相似的影响。 PHP: mktime -手动

正如一些人说的,strtotime并不是最可靠的方法,而且很少有像strtotime这样容易通用的方法。

其他回答

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

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

如果您使用的是32位系统,那么由于2038年问题,strtotime()代码将在2038年之后失败。

例如,在32位系统上,此代码将回显1970-01-31:

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

如果你需要你的代码支持32位系统,那么你应该使用DateTime函数:

$d = new DateTime('2040-11-23'); 
echo $d->format('Y-m-t');

该代码将在32位或64位系统上正确地输出2040-11-30。

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

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

来自另一个DateTime对象

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

这应该可以工作:

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