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

Wil*_*azi 22 php datetime

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

<?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));

?>
Run Code Online (Sandbox Code Playgroud)

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

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

Mih*_*rga 76

echo date('Y-m-d', strtotime('last day of previous month'));
//2012-09-30
Run Code Online (Sandbox Code Playgroud)

要么

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

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

  • 如果日期是2013-01-01,那么您的第一个答案是否仍然可以解决一年中的变化? (2认同)
  • 如果检查最后一个代码,那个带有`DateTime`的代码并将其更改为`$ date = new DateTime('2013-01-01');`它将输出:`2012-12-31` (2认同)
  • 为什么不`$ date = new\DateTime("上个月的最后一天");`? (2认同)

小智 20

这有一个PHP功能.

echo date("t/m/Y", strtotime("last month"));
Run Code Online (Sandbox Code Playgroud)

  • 't'=给定月份中的天数。http://php.net/manual/zh/function.date.php (2认同)
  • `strtotime(“ last month”);`[在每个月的31号]并没有真正起作用(https://gist.github.com/garak/1000118) (2认同)