How to use PHP to calculate the last month today

  • 2020-06-01 09:18:53
  • OfStack

1 day, encounter 1 problem, seek 1 month today. At the beginning, we used the strtotime(" -1 month ") function to evaluate the value. We found that there was a problem: the calculation result of a month with different month length was wrong. For example: 2011-03-31, you get 2011-03-03. Let's look at how to solve the problem rather than what the problem is. At this point, I remembered that there was an mktime function in PHP, so I wrote the following code:

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

When executed, the result is the same as strtotime's.
Again, based on this function, since we cannot directly manipulate the month, we start with the day, get the last month, and then use date to splice the data. The following code:

$time = strtotime("2011-03-31");
/**
 *  On the calculation 1 today 
 * @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);

But now there is another problem, there is no such date as 2011-02-31, how to do? The current requirement is for such a date to show the last day of the month. The following code:

 $time = strtotime("2011-03-31");
/**
 *  On the calculation 1 Today of the month. If there was no today last month, then go back up 1 At the end of the month 1 day 
 * @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);

One thing to note here: date(" Y-m ", $last_month_time). "-d". If you write "Y-". date(" m ", $last_month_time). "-d" has a problem with the time of the New Year. This was discovered while writing this article.
In addition to this method, you can figure out the year, month, and day before concatenating the string, which is a pure string operation.

Related articles: