6

Given a time, how can I find the time one month ago.

steven
  • 13,147
  • 16
  • 39
  • 39
  • By "one month" do you mean 30 days to the second? Or would you want to adjust for a 28 or 29-day February problem? –  Dec 30 '09 at 05:27
  • Can you be a little more specific? For example, if it's 2:00pm December 29th, wouldn't the time one month ago be 2:00pm November 29th? – justinl Dec 30 '09 at 05:27

7 Answers7

16
strtotime( '-1 month', $timestamp );

http://php.net/manual/en/function.strtotime.php

Galen
  • 29,976
  • 9
  • 71
  • 89
  • 3
    BEWARE: This will cause unexpected results at the end of 31 day months and March. http://derickrethans.nl/obtaining-the-next-month-in-php.html – Sherms Aug 01 '15 at 19:53
3

In php you can use strtotime("-1 month"). Check out the documentation here: http://ca3.php.net/strtotime

justinl
  • 10,448
  • 21
  • 70
  • 88
3

We can achieve same by using PHP's modern date handling. This will require PHP 5.2 or better.

// say its "2015-11-17 03:27:22"
$dtTm = new DateTime('-1 MONTH', new DateTimeZone('America/Los_Angeles')); // first argument uses strtotime parsing
echo $dtTm->format('Y-m-d H:i:s'); // "2015-10-17 03:27:22"

Hope this adds some more info for this question.

TheMohanAhuja
  • 1,855
  • 2
  • 19
  • 30
1
<?php

$date = new DateTime("18-July-2008 16:30:30");
echo $date->format("d-m-Y H:i:s").'<br />';

date_sub($date, new DateInterval("P1M"));
echo '<br />'.$date->format("d-m-Y").' : 1 Month';

?> 
Kirill V. Lyadvinsky
  • 97,037
  • 24
  • 136
  • 212
1

PHP 5.2=<

$date = new DateTime(); // Return Datetime object for current time
$date->modify('-1 month'); // Modify to deduct a month (Also can use '+1 day', '-2 day', ..etc)
echo $date->format('Y-m-d'); // To set the format 

Ref: http://php.net/manual/en/datetime.modify.php

Sadee
  • 3,010
  • 35
  • 36
1

This code is for getting 1 month before not 30 days

$date = "2016-03-31";

$days = date("t", strtotime($date));

echo  date("Y-m-d", strtotime( "-$days days", strtotime($date) ));
Davit Huroyan
  • 302
  • 4
  • 16
0

These answers were driving me nuts. You can't subtract 31 days and have a sane result without skipping short months. I'm presuming you only care about the month, not the day of the month, for a case like filtering/grouping things by year and month.

I do something like this:

$current_ym = date('ym',strtotime("-15 days",$ts));

poleguy
  • 523
  • 7
  • 11