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

标签 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));

?>

$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/

相关文章:

javascript - Moment.js 24小时时间格式,处理24小时

javascript - 如何使用 javascript 获取用户时区的字符串表示形式?

php - 如何在 SugarCRM 的电子邮件模板中使用条件

PHP:动态对象名称

php - PHP 搜索时漏掉一个字符怎么办?

python - 使用 pd.to_datetime 通过输入数据框中不同列中的年、月、日来形成日期

javascript - 使用 JQuery、Ajax 和 PHP 的登录处理程序

PHPDoc:如何记录不同的类属性选项

ruby-on-rails - 人性化时间

c# - Mongodb C# 按日期时间属性过滤