在PHP中查找上个月的最后一天 [英] Finding Last Day of Previous Month in PHP
问题描述
我有点不确定为什么无法找到上个月的最后一天.除了创建最终日期以外,每个步骤似乎都可以正常工作.
I'm a little unsure why this is not able to find the last day of the previous month. Every steps seems to be working correctly, except when the final date is created.
<?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日返回.我似乎在哪里出错了?
$lastDateOfPreviousMonth
is returning 2012-09-30 as expected; however, after trying to convert it to September 30, 2012 - $newLastDateOfMonth
is returning October 1, 2012. Where do I seem to be going wrong?
如果使用date("t/m/Y", strtotime("last month"));
或date('Y-m-d', strtotime('last day of previous month'));
,在2013年1月1日给出的建议中,这两种方法仍然可行,也就是说,它们是否会说明年份的变化?
If using date("t/m/Y", strtotime("last month"));
or date('Y-m-d', strtotime('last day of previous month'));
will either of these still be viable given 2013-01-01, i.e. will they account for the change in year?
推荐答案
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()
这篇关于在PHP中查找上个月的最后一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!