99

I want to get last month's date. I wrote this out:

$prevmonth = date('M Y');

Which gives me the current month/year. I can't tell if I should use strtotime, mktime. Something to the timestamp? Do I need to add something afterwards to reset so that the date isn't set to last month throughout everything for all timestamps on my site? I'm trying to RTM but it's hard for me to figure this out.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
pg.
  • 2,503
  • 4
  • 42
  • 67

18 Answers18

257

It's simple to get last month date

echo date("Y-n-j", strtotime("first day of previous month"));
echo date("Y-n-j", strtotime("last day of previous month"));

at November 3 returns

2014-10-1
2014-10-31
Josafat
  • 382
  • 3
  • 16
OzzyCzech
  • 9,713
  • 3
  • 50
  • 34
  • 9
    This one is not good enough and can cause errors in your code: `$time = strtotime('2011-03-30 01:01:01'); echo date('r', strtotime('-1 month', $time));` this one will return Wed, 02 Mar 2011 01:01:01 - not february! Use `strtotime('first day of previous month')` instead – Ostin Jun 06 '13 at 17:41
  • @OzzyCzech It returns October 1 and 31 when you run it on March 3? – The Unknown Dev Jan 06 '15 at 22:02
  • $data_day_str=strtotime("previous month",strtotime('2011-03-30 01:01:01')); You will get february of 2011. – Rodrigo Serzedello Dec 02 '19 at 02:21
  • Working well on my php version 7.4 – Bang Andre Mar 29 '23 at 07:55
39
echo strtotime("-1 month");

That will output the timestamp for last month exactly. You don't need to reset anything afterwards. If you want it in an English format after that, you can use date() to format the timestamp, ie:

echo date("Y-m-d H:i:s",strtotime("-1 month"));
zombat
  • 92,731
  • 24
  • 156
  • 164
  • 16
    Today is October 31, 2012. date("Y-m-d", strtotime("-1 month")); Returns 2012-10-01. :( – Todd Oct 31 '12 at 18:31
  • 7
    @toddsler Correct. -1 month is the very same as writing -30 days which on certain dates during the year will either skip 1 month or remain on the same month, so be careful with this method. – silkfire Oct 21 '13 at 09:20
  • 2
    DO NOT USE THIS SOLUTION! Previous comments are correct, you will have errors that will be triggered only on the 31th day of the month (or in 29,30,31 of march) – Teenage Jan 31 '20 at 15:30
  • 1
    Doesn't work if the day is 31st of the month, strtotime("first day of -1 month") it works perfectly – Adnen Chouibi Oct 31 '21 at 14:23
21

Incorrect answers are:

$lastMonth = date('M Y', strtotime("-1 month"));
$lastDate = date('Y-m', strtotime('last month'));

The reason is if current month is 30+ days but previous month is 29 and less $lastMonth will be the same as current month.

e.g.

If $currentMonth = '30/03/2016';
echo $lastMonth = date('m-Y', strtotime("-1 month")); => 03-2016
echo $lastDate = date('Y-m', strtotime('last month')); => 2016-03

The correct answer will be:

echo date("m-Y", strtotime("first day of previous month")); => 02-2016
echo sprintf("%02d",date("m")-1) . date("-Y"); => 02-2016
echo date("m-Y",mktime(0,0,0,date("m")-1,1,date("Y"))); => 02-2016
Fury
  • 4,643
  • 5
  • 50
  • 80
  • 3
    I would upvote if you remove echo sprintf("%02d",date("m")-1) . date("-Y"); => 02-2016. If we are in january, it answers month 0 of this year, not 12 of last year ! – Tama Jul 31 '19 at 13:33
  • very correct answer, all other answers brings thirty days from today – Nasz Njoka Sr. Dec 08 '22 at 08:45
20
$prevmonth = date('M Y', strtotime("last month"));
Scharrels
  • 3,055
  • 25
  • 31
  • 4
    This is the same as date('M Y', strtotime("-1 month")), if you do something like date('M Y', strtotime("2017-07-31 last month")) it will return 2017-07-01, so be careful! date('M Y', strtotime('2017-07-31 first day of previous month')) would give you what you want – Shadoweb Aug 01 '17 at 11:01
6

if you want to get just previous month, then you can use as like following

$prevmonth = date('M Y', strtotime('-1 months'));

if you want to get same days of previous month, Then you can use as like following ..

$prevmonth = date('M Y d', strtotime('-1 months'));

if you want to get last date of previous month , Then you can use as like following ...

$prevmonth = date('M Y t', strtotime('-1 months'));

if you want to get first date of previous month , Then you can use as like following ...

$prevmonth = date('M Y 1', strtotime('-1 months'));
6

Found this one wrong when the previous months is shorter than current.

echo date("Y-m-d H:i:s",strtotime("-1 month"));

Try on March the 30th and you will get 2012-03-01 instead of 2012-02...

Working out on better solution...

Jay_69
  • 87
  • 1
  • 2
6
echo date('Y',strtotime("-1 year"));        //last year<br>
echo date('d',strtotime("-1 day"));     //last day<br>
echo date('m',strtotime("-1 month"));       //last month<br>
Shafiqul Islam
  • 5,570
  • 2
  • 34
  • 43
Vaishu
  • 2,333
  • 3
  • 23
  • 25
  • 3
    This answer is not correct when the current date is 2018/03/31. Detail also like [this](https://stackoverflow.com/a/36310666/6351894) – Ngoc Nam Mar 30 '18 at 16:45
4
public function getLastMonth() {
    $now = new DateTime();
    $lastMonth = $now->sub(new DateInterval('P1M'));
    return $lastMonth->format('Ym');
}
  • 1
    Wont work for `2015-10-31` in PHP 5.5 and 5.6.11. You will get `201510` - same behavior as with `strtotime('- 1 month)`. – pmayer Nov 03 '15 at 12:35
2

Use this short code to get previous month for any given date:

$tgl = '25 january 2012';

$prevmonth = date("M Y",mktime(0,0,0,date("m", strtotime($tgl))-1,1,date("Y", strtotime($tgl))));
echo $prevmonth;

The result is December 2011. Works on a month with shorter day with previous month.

Abdul Rahman
  • 2,097
  • 4
  • 28
  • 36
abdul
  • 21
  • 1
2
$lastMonth = date('M Y', strtotime("-1 month"));
var_dump($lastMonth);
$lastMonth = date('M Y', mktime(0, 0, 0, date('m') - 1, 1, date('Y')));
var_dump($lastMonth);
bloody numen
  • 487
  • 6
  • 13
  • 4
    While code itself can be somewhat self explanatory, it is helpful to other users to explain your answer rather than just giving code. – Turnerj Aug 26 '15 at 08:24
2

Simply get last month.

Example:

Today is: 2020-09-02

Code:

echo date('Y-m-d', strtotime(date('Y-m-d')." -1 month"));

Result:

2020-08-02

xKobalt
  • 1,498
  • 2
  • 13
  • 19
  • Welcome to StackOverflow! Probably, you should also consider to explain what happens if the day is `31` and the month is not January or August (like `2020 May 31` becomes `2020 April 31`, that does not exist) – xKobalt Sep 02 '20 at 13:19
  • php builtin function "date", handle it. – SL-phpdeveloper Nov 06 '20 at 11:09
1

Oh I figured this out, please ignore unless you have the same problem i did in which case:

$prevmonth = date("M Y",mktime(0,0,0,date("m")-1,1,date("Y")));
Taryn
  • 242,637
  • 56
  • 362
  • 405
pg.
  • 2,503
  • 4
  • 42
  • 67
1

You can use strtotime, which is great in this kind of situations :

$timestamp = strtotime('-1 month');
var_dump(date('Y-m', $timestamp));

Will get you :

string '2009-11' (length=7)
Pascal MARTIN
  • 395,085
  • 80
  • 655
  • 663
1

This question is quite old but here goes anyway. If you're trying to get just the previous month and the day does not matter you can use this:

$date = '2014-01-03';

$dateTime = new DateTime($date);

$lastMonth = $dateTime->modify('-' . $dateTime->format('d') . ' days')->format('F Y');

echo $lastMonth; // 'December 2013'
Jay Kravetz
  • 233
  • 2
  • 10
1

The best solution I have found is this:

function subtracMonth($currentMonth, $monthsToSubtract){
        $finalMonth = $currentMonth;
        for($i=0;$i<$monthsToSubtract;$i++) {
            $finalMonth--;
            if ($finalMonth=='0'){
                $finalMonth = '12';
            }

        }
        return $finalMonth;

    }

So if we are in 3(March) and we want to subtract 5 months that would be

subtractMonth(3,5);

which would give 10(October). If the year is also desired, one could do this:

function subtracMonth($currentMonth, $monthsToSubtract){
    $finalMonth = $currentMonth;
    $totalYearsToSubtract = 0;
    for($i=0;$i<$monthsToSubtract;$i++) {
        $finalMonth--;
        if ($finalMonth=='0'){
            $finalMonth = '12';
            $totalYearsToSubtract++;
        }

    }
    //Get $currentYear
    //Calculate $finalYear = $currentYear - $totalYearsToSubtract 
    //Put resulting $finalMonth and $finalYear into an object as attributes
    //Return the object

}
1
$time = mktime(0, 0, 0, date("m"),date("d")-date("t"), date("Y"));
$lastMonth = date("d-m-Y", $time);

OR

$lastMonth = date("m-Y", mktime() - 31*3600*24);

works on 30.03.2012

Juan Mellado
  • 14,973
  • 5
  • 47
  • 54
Paul
  • 11
  • 1
0

If you want to get first date of previous month , Then you can use as like following ... $prevmonth = date('M Y 1', strtotime('-1 months')); what? first date will always be 1 :D

Tony Stark
  • 8,064
  • 8
  • 44
  • 63
0

It works for me:

Today is: 31/03/2012

echo date("Y-m-d", strtotime(date('m', mktime() - 31*3600*24).'/01/'.date('Y').' 00:00:00')); // 2012-02-01
echo  date("Y-m-d", mktime() - 31*3600*24); // 2012-02-29
  • In only works in 58.3(3)% of cases. What about February, April, Jun, September and November? They do not have 31 days. – Taz Oct 26 '12 at 14:42