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

考虑到:

$a_date = "2009-11-23"

我想要2009-11-30;鉴于

$a_date = "2009-12-23"

我要2009-12-31。


当前回答

如果你使用碳API扩展PHP DateTime,你可以得到一个月的最后一天:

$date = Carbon::now();
$date->addMonth();
$date->day = 0;
echo $date->toDateString(); // use toDateTimeString() to get date and time 

其他回答

你的解决方案在这里。

$lastday = date('t',strtotime('today'));

这应该可以工作:

$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/>';

这是一个完整的函数:

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

对我来说,最优雅的是使用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'));