PHP subtracts 1 month from the day formed with the date ('mY')

I am trying to subtract 1 month from the date.

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

It gives: 08-2016

How can I deduct a month to get 07-2016 ?

+18
source share
8 answers
  <?php echo $newdate = date("mY", strtotime("-1 months")); 

Exit

 07-2016 
+36
source

Warning! The above examples will not work if you call them at the end of the month.

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

will output:

 10-2017 10-2017 

The following example will give the same result:

 $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"; 

Many ways to solve the problem can be found in another thread: PHP DateTime :: change the time of adding and subtracting

+8
source

Try it,

 $today = date('m-Y'); $newdate = date('m-Y', strtotime('-1 months', strtotime($today))); echo $newdate; 
+3
source

Depending on your version of PHP, you can use a DateTime object (introduced in PHP 5.2, if I remember correctly):

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

You can pass another date to the constructor, it should not be the current date. Additional information: http://php.net/manual/en/datetime.modify.php

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

First change the date format from YY to YM

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

This code minus 1 month before the specified date

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

Try this,

 $effectiveDate = date('2018-01'); <br> echo 'Date'.$effectiveDate;<br> $effectiveDate = date('m-y', strtotime($effectiveDate.'+-1 months'));<br> echo 'Date'.$effectiveDate; 
0
source

All Articles