zoukankan      html  css  js  c++  java
  • 【转】使用PHP计算上一个月的今天

    转自:http://www.phppan.com/2011/06/php-last-month-today/

    一日,遇到一个问题,求上一个月的今天。 最开始我们使用 strtotime(”-1 month”) 函数求值,发现有一个问题,月长度不一样的月份的计算结果有误。 比如:2011-03-31,得到的结果是2011-03-03。我们先不追究什么问题,先看如何解决问题。 此时,想起PHP中有一个mktime函数,于是自己写了如下代码:

    echo date("Y-m-d H:i:s", mktime(date("G", $time), date("i", $time),
     date("s", $time), date("n", $time) - 1, date("j", $time), date("Y", $time)));

    当执行时,发现结果和strtotime的结果是一样的。

    还是基于这个函数,既然无法直接操作月,那么我们从天入手,得到上一个月,然后再使用date拼接数据。如下代码:

    $time = strtotime("2011-03-31");
    
    /**
     * 计算上一个月的今天
     * @param type $time
     * @return type
     */
    function last_month_today($time) {
         $last_month_time = mktime(date("G", $time), date("i", $time),
                    date("s", $time), date("n", $time), - 1, date("Y", $time));
         return date(date("Y-m", $last_month_time) . "-d H:i:s", $time);
    }
    
    echo last_month_today($time);

    但是此时又有了另一个问题,不存在2011-02-31这样的日期,怎么办?现在的需求是对于这样的日期显示当月最后一天。 如下代码:

     $time = strtotime("2011-03-31");
    
    /**
     * 计算上一个月的今天,如果上个月没有今天,则返回上一个月的最后一天
     * @param type $time
     * @return type
     */
    function last_month_today($time){
        $last_month_time = mktime(date("G", $time), date("i", $time),
                    date("s", $time), date("n", $time), 0, date("Y", $time));
        $last_month_t =  date("t", $last_month_time);
    
        if ($last_month_t < date("j", $time)) {
            return date("Y-m-t H:i:s", $last_month_time);
        }
    
        return date(date("Y-m", $last_month_time) . "-d", $time);
    }
    
    echo last_month_today($time);

    这里需要注意一点: date(”Y-m”, $last_month_time) . “-d”这段代码。在写代码的过程中如果写成了 “Y-” . date(”m”, $last_month_time) . “-d” 则在跨年的时间上有问题。 这点还是在写这篇文章时发现的。

    除了这种方法,还可以先算出年月日再拼接字符串,这里就是纯粹的字符串操作了。

    感触:

    • 一个月不写代码,会手生。
    • 代码写完后请多次review或重构,即使比较简单的代码。
  • 相关阅读:
    Bootstrap历练实例:输入框组的大小
    bootstrap历练实例:复选框或单选按钮作为输入框组的前缀或后缀
    bootstrap历练实例:按钮作为输入框组前缀或后缀
    Bootstrap历练实例:垂直的按钮组
    [uiautomator篇][exist 存在,但click错误]
    [python篇][1]configparser 问题汇总
    [python篇][其他] python博客学习汇总
    [uiautomator篇][8] 增加应用读取内置存储卡的权限
    [uiautomator篇] 使用uiautomator需要导入uiautomator库
    [uiautomator篇][9]遇到问题
  • 原文地址:https://www.cnblogs.com/fzzl/p/2848035.html
Copyright © 2011-2022 走看看