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

考虑到:

$a_date = "2009-11-23"

我想要2009-11-30;鉴于

$a_date = "2009-12-23"

我要2009-12-31。


当前回答

您也可以将它与datetime一起使用

$date = new \DateTime();
$nbrDay = $date->format('t');
$lastDay = $date->format('Y-m-t');

其他回答

这是一个完整的函数:

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

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

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

另一种使用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

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

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

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

$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这样容易通用的方法。