在 PHP 中查找上个月的最后一天

2022-08-30 14:39:35

我有点不确定为什么这无法找到上个月的最后一天。每个步骤似乎都正常工作,除非创建了最终日期。

<?php

$currentMonth = date('n');
$currentYear = date('Y');

if($currentMonth == 1) {
    $lastMonth = 12;
    $lastYear = $currentYear - 1;
}
else {
    $lastMonth = $currentMonth -1;
    $lastYear = $currentYear;
}

if($lastMonth < 10) {
    $lastMonth = '0' . $lastMonth;
}

$lastDayOfMonth = date('t', $lastMonth);

$lastDateOfPreviousMonth = $lastYear . '-' . $lastMonth . '-' . $lastDayOfMonth;

$newLastDateOfMonth = date('F j, Y', strtotime($lastDateOfPreviousMonth));

?>

$lastDateOfPreviousMonth正在返回 2012-09-30 如预期;但是,在尝试将其转换为2012年9月30日后 - 将于2012年10月1日返回。我哪里似乎出错了?$newLastDateOfMonth

编辑:如果使用或其中任何一个仍然可行,鉴于2013-01-01,即它们是否会考虑年份的变化?date("t/m/Y", strtotime("last month"));date('Y-m-d', strtotime('last day of previous month'));


答案 1
echo date('Y-m-d', strtotime('last day of previous month'));
//2012-09-30

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

后期编辑:php.net 文档 - strtotime(),DateTime和date_create()的相对格式


答案 2

有一个php函数可以做到这一点。

echo date("t/m/Y", strtotime("last month"));

推荐