php 计算上一个月的今天 PHP 计算几个月前的今天

PHP 计算几个月前的今天    

下面第一个方法基本全覆盖了所需功能

/*
 * 根据指定时间 计算指定前N个月的今天
 * */
function lastMonth($nowT,$i){
    $lastM1 = date('n', strtotime(" -" . $i . " month", strtotime("first day of 0 month", $nowT)));
    $lastM2 = date('n', strtotime(" -" . $i . " month", $nowT));
    if ($lastM1 != $lastM2) {
        $expectD = date('Y-m-d', strtotime(" last day of -" . $i . " month", $nowT));
    } else {
        $expectD = date('Y-m-d', strtotime(" -" . $i . " month", $nowT));
    }
    return $expectD;
}

下面这个方法只是适用于调取上个月的今天

/**
 * 计算上一个月的今天,如果上个月没有今天,则返回上一个月的最后一天
 * @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);
}
  $time = strtotime("2021-05-31");//time();
  $aa = last_month_today($time);
  dump($aa);die();
原文地址:https://www.cnblogs.com/zc290987034/p/14498087.html