How to remove 3 months from a date?

Assume date:

$date = "2011-08-28"; 

It is necessary to calculate 3 months before $date - how can this be done?

+6
source share
5 answers
 $new_timestamp = strtotime('-3 months', strtotime($date)); 

Then you can use the new timestamp using the php date () function to display the new date as you want, for example:

 echo date("Ymd",$new_timestamp); 
+15
source

For me, this method is much better, because the code is more readable.

 $datetime = Datetime::createFromFormat('Ym-d', "2011-08-28"); $datetime->modify('-3 months'); echo $datetime->format('Ym-d'); 

edit: I'm an idiot. You can do the following:

 $datetime = new Datetime("2011-08-28"); $datetime->modify('-3 months'); echo $datetime->format('Ym-d'); 
+11
source

edit: as calumbrodie points out, you can use the sub method instead of inverting the interval and adding it to the date object


I tried to do something similar to the original question. I needed to subtract 1 day from a DateTime object. I know that other solutions work, but here I liked the other way more. I used this function:

 function getPreviousDay($dateObject){ $interval = new DateInterval('P1D'); $dateObject->sub($interval); return $dateObject; } 

$ dateObject is a DateTime object that can have any date you don't want, but since I wanted the current date, I wrote:

 $dateObject = new DateTime('now'); 

My function subtracts 1 day from the received date, but you can change it to subtract 3 months by modifying the DateInterval constructor as follows:

 $interval = new DateInterval('P3M'); $dateObject->sub($interval); return $dateObject; 

You can find an explanation of the string format used in the DateInterval constructor, here

DateInterval constructor documentation

There you will see that the letter β€œP” (period) is mandatory if you use int to indicate the length of the period, and then specify the type of period, in the case of months β€œM”. It seems that an error has occurred in the documentation, it says that "M" is used for months and minutes, but actually works for months. If you need to use the minutes, you must specify "PTM", for example, "PT3M" for 3 minutes, outside the table it is indicated that you should use the identifier "T" for time intervals.

edit: to give a complete example, you should use this format for the full date time interval:

 $format = 'P1Y2M4DT2H1M40S'; 

This will represent an interval of 1 year, 2 months, 4 days, 2 hours, 1 minute and 40 seconds.

Hope this helps someone

+3
source
 <?php $threemonthsago = mktime(0, 0, 0, date("m")-3, date("d"), date("Y")); ?> 
+2
source
 <?php $date = date_create('2000-01-01'); date_add($date, date_interval_create_from_date_string('10 days')); echo date_format($date, 'Ym-d'); ?> 
0
source

All Articles