Getting last month's date in php
Asked Answered
E

19

100

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.

Execute answered 11/12, 2009 at 17:52 Comment(0)
L
260

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
Latia answered 3/3, 2011 at 12:32 Comment(4)
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') insteadPolyp
@Latia It returns October 1 and 31 when you run it on March 3?Countershading
$data_day_str=strtotime("previous month",strtotime('2011-03-30 01:01:01')); You will get february of 2011.Dorkas
Working well on my php version 7.4Morula
T
40
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"));
Twilley answered 11/12, 2009 at 17:53 Comment(4)
Today is October 31, 2012. date("Y-m-d", strtotime("-1 month")); Returns 2012-10-01. :(Introductory
@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.Domenicadomenico
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)Woolsack
Doesn't work if the day is 31st of the month, strtotime("first day of -1 month") it works perfectlyDichroite
L
22

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
Lexicography answered 30/3, 2016 at 13:42 Comment(2)
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 !Riocard
very correct answer, all other answers brings thirty days from todayRocky
S
20
$prevmonth = date('M Y', strtotime("last month"));
Submediant answered 11/12, 2009 at 17:55 Comment(1)
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 wantActinomycin
M
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...

Marolda answered 30/3, 2012 at 7:38 Comment(3)
This answer is correct (-1 month won't work properly in all cases). For the previous month, use strtotime('last month').Abney
Last month or -1 month returns the same value.Gussiegussman
Doesn't work if the day is 31st of the month, strtotime("first day of -1 month") it works perfectlyDichroite
V
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>
Vicegerent answered 30/3, 2012 at 9:29 Comment(1)
This answer is not correct when the current date is 2018/03/31. Detail also like thisCerallua
L
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'));
Lordosis answered 13/1, 2013 at 7:38 Comment(2)
Be careful for the 31st of the month! It will give you the 1st of the current month! See above.Actinomycin
Doesn't work if the day is 31st of the month, strtotime("first day of -1 month") it works perfectlyDichroite
M
4
public function getLastMonth() {
    $now = new DateTime();
    $lastMonth = $now->sub(new DateInterval('P1M'));
    return $lastMonth->format('Ym');
}
Mayence answered 19/4, 2012 at 7:33 Comment(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).Roup
G
3

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

Gaynellegayner answered 2/9, 2020 at 10:16 Comment(2)
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)Pareu
php builtin function "date", handle it.Gaynellegayner
T
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.

Trudi answered 31/5, 2012 at 10:0 Comment(0)
B
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);
Boudoir answered 26/8, 2015 at 5:46 Comment(1)
While code itself can be somewhat self explanatory, it is helpful to other users to explain your answer rather than just giving code.Lotty
E
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")));
Execute answered 11/12, 2009 at 17:55 Comment(0)
T
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)
Trypanosomiasis answered 11/12, 2009 at 17:55 Comment(0)
E
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

Evieevil answered 30/3, 2012 at 9:34 Comment(0)
B
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'
Brocade answered 3/11, 2014 at 18:32 Comment(0)
T
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

}
Tournedos answered 14/7, 2020 at 21:19 Comment(0)
U
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
Uniat answered 31/3, 2012 at 16:27 Comment(1)
In only works in 58.3(3)% of cases. What about February, April, Jun, September and November? They do not have 31 days.Epilate
O
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

Outherod answered 4/10, 2013 at 11:20 Comment(1)
October 31, 2012. Returns 2012-10-01Hakon
N
0

Similar to the accepted answer, but using DateTime(), so you don't need to define the output format when initialised.

$start = new \DateTime('first day of previous month');
$end = new \DateTime('last day of previous month');
Naturism answered 21/3 at 0:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.