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

考虑到:

$a_date = "2009-11-23"

我想要2009-11-30;鉴于

$a_date = "2009-12-23"

我要2009-12-31。


当前回答

对我来说,最优雅的是使用DateTime

我不知道我没有看到DateTime::createFromFormat,一行程序

$lastDay = \DateTime::createFromFormat("Y-m-d", "2009-11-23")->format("Y-m-t");

其他回答

我使用strtotime与cal_days_in_month如下所示:

$date_at_last_of_month=date('Y-m-d', strtotime('2020-4-1
+'.(cal_days_in_month(CAL_GREGORIAN,4,2020)-1).' day'));

你可以用几种方法找到这个月的最后一天。但是,您可以简单地使用PHP strtotime()和date()函数来实现这一点。我认为你的最终代码应该是这样的:

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

现场演示

但是如果你正在使用PHP >= 5.2,我强烈建议你使用新的DateTime对象。例如:

$a_date = "2009-11-23";
$date = new DateTime($a_date);
$date->modify('last day of this month');
echo $date->format('Y-m-d');

现场演示

此外,你可以使用自己的函数来解决这个问题,如下所示:

/**
 * Last date of a month of a year
 *
 * @param[in] $date - Integer. Default = Current Month
 *
 * @return Last date of the month and year in yyyy-mm-dd format
 */
function last_day_of_the_month($date = '')
{
    $month  = date('m', strtotime($date));
    $year   = date('Y', strtotime($date));
    $result = strtotime("{$year}-{$month}-01");
    $result = strtotime('-1 second', strtotime('+1 month', $result));

    return date('Y-m-d', $result);
}

$a_date = "2009-11-23";
echo last_day_of_the_month($a_date);

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

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

碳API扩展PHP DateTime

Carbon::parse("2009-11-23")->lastOfMonth()->day;

or

Carbon::createFromDate(2009, 11, 23)->lastOfMonth()->day;

将返回

30

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

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

来自另一个DateTime对象

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