Get previous month value in PHP

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

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

It worked fine, and until yesterday I was getting a value of 04 . Today is May 31 (the last day of the month of May), I noticed that the function returns only the current month. This is 05 . Is there another alternative function that accurately returns the previous month.

+5
source share
5 answers

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

first day of is an important part as detailed here.

+2
source

Literally ask strtotime for the "first day of the previous month", this ensures that it selects the correct month: -

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

You can use OOP with the DateTime class and change the method:

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

strtotime() works exactly . The problem is that you are asking her to return.

"- 1 month" does not match the "previous month". This is the same as "subtract 1 from the current month, and then normalize the result."

In 2017-05-31 subtracting 1 from the current month receives 2017-04-31 , which is not a valid date. After normalization, it becomes 2017-05-01 , hence the result is obtained.

There are several ways to get the desired value. For instance:

 // 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('Ym-d')); // On 2017-05-31 it should print: // 2017-04-01 
+2
source

If you just need to get the month number in the previous month, the following should be enough.

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

This works with an arbitrary number of deductible months.

0
source

Source: https://habr.com/ru/post/1268394/


All Articles