PHP 从日期格式中减去 1 个月 ('m-Y')

PHP subtract 1 month from date formatted with date ('m-Y')

我正在尝试从日期中减去 1 个月。

$today = date('m-Y');

这给出:08-2016

如何减去一个月得到07-2016

试试这个,

$today = date('m-Y');
$newdate = date('m-Y', strtotime('-1 months', strtotime($today))); 
echo $newdate;
 <?php 
  echo $newdate = date("m-Y", strtotime("-1 months"));

输出

07-2016

根据您的 PHP 版本,您可以使用 DateTime 对象(如果我没记错的话,在 PHP 5.2 中引入):

<?php
$today = new DateTime(); // This will create a DateTime object with the current date
$today->modify('-1 month');

您可以将另一个日期传递给构造函数,它不必是当前日期。更多信息:http://php.net/manual/en/datetime.modify.php

警告!如果在月底调用上述示例,将无法正常工作。

<?php
$now = mktime(0, 0, 0, 10, 31, 2017);
echo date("m-Y", $now)."\n";
echo date("m-Y", strtotime("-1 months", $now))."\n";

将输出:

10-2017
10-2017

以下示例将产生相同的结果:

$date = new DateTime('2017-10-31 00:00:00');
echo $date->format('m-Y')."\n";
$date->modify('-1 month');
echo $date->format('m-Y')."\n";

在另一个线程中可以找到许多解决问题的方法:PHP DateTime::modify adding and subtracting months

if(date("d") > 28){
    $date = date("Y-m", strtotime("-".$loop." months -2 Day"));
} else {
    $date = date("Y-m", strtotime("-".$loop." months"));
}
$lastMonth = date('Y-m', strtotime('-1 MONTH'));

先把日期格式m-Y改成Y-m

    $date = $_POST('date'); // Post month
    or
    $date = date('m-Y'); // currrent month

    $date_txt = date_create_from_format('m-Y', $date);
    $change_format = date_format($date_txt, 'Y-m');

此代码减去给定日期的 1 个月

    $final_date = new DateTime($change_format);
    $final_date->modify('-1 month');
    $output = $final_date->format('m-Y');

试试这个,

$effectiveDate = date('2018-01'); <br> 
echo 'Date'.$effectiveDate;<br>
$effectiveDate = date('m-y', strtotime($effectiveDate.'+-1 months'));<br>
echo 'Date'.$effectiveDate;
$currentMonth = date('m', time());
$currentDay = date('d',time());
$currentYear = date('Y',time());
$lastMonth = $currentMonth -1;
$one_month_ago=mkdate(0,0,0,$one_month_ago,$currentDay,$currentYear);

这可以更优雅地重写,但它对我有用

我用它来防止“一个月的最后几天”错误。我只是使用第二个 strtotime() 将日期设置为该月的第一天:

<?php
echo $newdate = date("m-Y", strtotime("-1 months", strtotime(date("Y-m")."-01")));