Home » Php » Get previous month value in PHP

Get previous month value in PHP

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have used the below PHP function to get the previous month,

$currmonth = date('m', strtotime('-1 month'));

It was working fine and I was getting the value of 04 till yesterday. On today May 31st (Last day of the month May), I noticed the function returns the current month only. That is 05. Is there any other alternate function which returns the previous month accurately.

How to&Answers:

Try strtotime("first day of last month").

The first day of is the important part as detailed here.

Answer:

You can use OOP with DateTime class and modify method:

$now = new DateTime();
$previousMonth = $now->modify('first day of previous month');
echo $previousMonth->format('m');

Answer:

Literally ask strtotime for the ‘first day of the previous month’ this makes sure it selects the correct month:-

$currmonth = date("m", strtotime("first day of previous month"));

Answer:

strtotime() works accurately. The problem is what you ask it to return.

“-1 month” is not the same as “previous month”. It is the same as “subtract 1 from current month then normalize the result”.

On 2017-05-31, subtracting 1 from current month gets 2017-04-31 which is not a valid date. After normalization, it becomes 2017-05-01, hence the result you get.

There are more than one way to get the value you need. For example:

// Today
$now = new DateTime('now');
// Create a date interval string to go back to the first day of the previous month
$int = sprintf('P1M%dD', $now->format('j')-1);
// Get the first day of the previous month as DateTime
$fdopm = $now->sub(new DateInterval($int));
// Verify it works
echo($fdopm->format('Y-m-d'));

// On 2017-05-31 it should print:
// 2017-04-01

Answer:

If you just need to get the month number of previous month, the following should suffice.

$m = idate("m") - 1;
// wrap to previous year
if ($m < 1) {
    $m = 12 - abs($m) % 12;
}

This works with arbitrary number of subtracted months.