【问题标题】:Grab last day of last month in PHP [duplicate]在PHP中获取上个月的最后一天[重复]
【发布时间】:2012-11-29 05:35:54
【问题描述】:

可能重复:
PHP last day of the month

在 PHP 中,我试图获取上个月的最后一天。 例如,今天是 2012 年 12 月 11 日。所以我想抓住的日期是 11 月 30 日。

这是我目前正在尝试做的:

        //this grabs the last daye of this month
        $current_month = date('Y-m-t',strtotime('today'));

        //this should grab November 30th.
        $last_month = date("F, Y",strtotime($current_month." -1 month ")

它没有抓住 11 月 30 日,而是抓住了 12 月 1 日。似乎“-1 个月”只是减去 30 天。

如何正确抓取上个月的最后一天?

【问题讨论】:

    标签: php date datetime time


    【解决方案1】:
    $datetime = new DateTime('last day of this month');
    echo $datetime->format('F jS');
    

    $datetime = new DateTime();
    echo $datetime->format('Y-m-t');
    

    第一个允许您随意格式化输出。如果您想使用不是当前月份的月份,您可以将 DateTime 构造函数传递给 valid date format,然后代码将完成剩下的工作。

    【讨论】:

    • 我在 PHP/5.4.5 Windows 上收到 Failed to parse time string。也许它需要捆绑在 Linux 中的时间库 :-?
    • 我收到服务器错误,我正在运行最新版本的 php
    • 我修改了我的答案以使用可能对每个人都更有效的替代方法
    【解决方案2】:

    cal_days_in_month() 是你想要的。最后一天与总天数相同。

    cal_days_in_month (int $calendar,int $month,int $year)
    

    $calendar 通常是 CAL_GREGORIAN

    将 $month - 1 发送到函数以获得所需的结果。

    【讨论】:

      【解决方案3】:

      您可以使用当前月份/年份和0 作为日期致电mktime()

      $last_day_of_last_month = mktime(0, 0, 0, date('n'), 0, date('Y'));
      

      记录在案:

      day [...] 小于 1 的值(包括负值)参考上个月的天数,因此 0 是上个月的最后一天 月,-1 是前一天,等等。值大于数字 相关月份的天数 下个月。

      【讨论】:

        猜你喜欢
        • 2013-11-25
        • 2016-01-13
        • 1970-01-01
        • 2015-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-27
        相关资源
        最近更新 更多