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

考虑到:

$a_date = "2009-11-23"

我想要2009-11-30;鉴于

$a_date = "2009-12-23"

我要2009-12-31。


当前回答

你可以用几种方法找到这个月的最后一天。但是,您可以简单地使用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);

其他回答

$date1 = $year.'-'.$month; 
$d = date_create_from_format('Y-m',$date1); 
$last_day = date_format($d, 't');

还有一个内置的PHP函数cal_days_in_month()?

"此函数将返回指定日历的某月中的天数。" http://php.net/manual/en/function.cal-days-in-month。

echo cal_days_in_month(CAL_GREGORIAN, 11, 2009); 
// = 30

我需要下个月的最后一天,也许有人会需要它:

echo date("Y-m-t", strtotime("next month")); //is 2020-08-13, return 2020-09-30

你可以用几种方法找到这个月的最后一天。但是,您可以简单地使用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);

您可以在日期函数中使用“t”来获得特定月份中的天数。

代码是这样的:

function lastDateOfMonth($Month, $Year=-1) {
    if ($Year < 0) $Year = 0+date("Y");
    $aMonth         = mktime(0, 0, 0, $Month, 1, $Year);
    $NumOfDay       = 0+date("t", $aMonth);
    $LastDayOfMonth = mktime(0, 0, 0, $Month, $NumOfDay, $Year);
    return $LastDayOfMonth;
}

for($Month = 1; $Month <= 12; $Month++)
    echo date("Y-n-j", lastDateOfMonth($Month))."\n";

代码是自解释的。希望这能有所帮助。