我有点不确定为什么无法找到上个月的最后一天。除了创建最终日期之外,每个步骤似乎都在正常工作。
<?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 日之后 - $newLastDateOfMonth
将返回 2012 年 10 月 1 日。我似乎哪里出错了?
编辑:如果使用 date("t/m/Y", strtotime("last month"));
或 date('Y-m-d', strtotime('last day上个月'));
考虑到 2013-01-01,这些中的任何一个是否仍然可行,即它们是否会考虑年份的变化?
最佳答案
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 documentation - relative formats for strtotime(), DateTime and date_create()
关于php - 在 PHP 中查找上个月的最后一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12674041/