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

考虑到:

$a_date = "2009-11-23"

我想要2009-11-30;鉴于

$a_date = "2009-12-23"

我要2009-12-31。


当前回答

如果你想回到几个月前,你也可以这样做。

 $list = [
        0, 1, 2, 3
    ];

    $date = new \Datetime();
    $dates = [];
    foreach($list as $item)
    {

        $set = clone $date;
        $set->modify("-$item month ");
       $dates[] = $set->modify("last day of this month");
       
    }
    return $dates;

其他回答

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

试试这个,如果你使用的是PHP 5.3+,

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

为了查找下个月最后的日期,修改如下:

 $date->modify('last day of 1 month');
 echo $date->format('Y-m-d');

等等。

如果您使用的是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。

如果你想回到几个月前,你也可以这样做。

 $list = [
        0, 1, 2, 3
    ];

    $date = new \Datetime();
    $dates = [];
    foreach($list as $item)
    {

        $set = clone $date;
        $set->modify("-$item month ");
       $dates[] = $set->modify("last day of this month");
       
    }
    return $dates;

我在这里将它包装在我的日期时间助手类中 https://github.com/normandqq/Date-Time-Helper 使用 $dateLastDay = Model_DTHpr::getLastDayOfTheMonth();

完成了