0

I have this:

$previousMonth = new DateTime('2019-12-31');
$previousMonth->modify('-1 month');

My understanding is '-1 month' should modify the object regardless of number of days in that month, or?

Naturally what should I get or expect to get is end of Nov(2019-11-30) but what I get is first of December(the same month). BTW if I change the date to '2019-12-30'(one day prior) then it will be end of Nov.

If my initial assumption is not correct, then what is the best alternative to reliably calculate the previous month? Any thoughts?

ZeitWert
  • 9
  • 1
  • How do you want to get *previous month* ? The last day of the previous month, whatever the date ? `'2019-12-15' '-1 month'` should give `2019-11-30` or `2019-11-15`? – Cid Jan 09 '20 at 09:15
  • @Cid Correct, independent of day, it should give me the previous month, any ideas? – ZeitWert Jan 09 '20 at 09:17
  • 1
    Does this answer your question? [PHP DateTime::modify adding and subtracting months](https://stackoverflow.com/questions/3602405/php-datetimemodify-adding-and-subtracting-months). This was already explained numerous times here at SO, didn't you look? This happens because `2019-11-31` doesn't exist, instead you end up with `2019-12-01` – Mike Doe Jan 09 '20 at 09:42

3 Answers3

0

The simplest and easiest way to get the last month in php is

$previousMonth = date("Y-n-j", strtotime("last day of previous month"));

Same as been suggested on other thread Getting last month's date in php

Swatantra Kumar
  • 1,324
  • 5
  • 24
  • 32
0
$date = "2019-12-31 00:00:00";
echo date('Y-m-d', strtotime($date . '-1month'));

This prints out 2019-12-01 as the 31/11 does not exist.

The following doesn't answer your question but may help in the future. I like to use Carbon when working with dates. Your issue could be resolved quite simply with this.

https://carbon.nesbot.com/

It has many functions and is extremely simple to use, and it can be installed with Composer.

Tj Hodge
  • 33
  • 5
-1

To get the last day of the previous month, you can get the first day of the current month and substract 1 second or 1 day :

$previousMonth = new DateTime('2019-12-31');
$previousMonth->modify($previousMonth->format('Y-m-01')); // date is 2019-12-01 00:00:00
$previousMonth->modify('-1 sec');
echo $previousMonth->format('Y-m-d H:i:s') . PHP_EOL; // Outputs 2019-11-30 23:59:59

$previousMonth->modify('+1 sec'); // set back the original date 2019-12-01 00:00:00
$previousMonth->modify('-1 day');
echo $previousMonth->format('Y-m-d H:i:s'); // Outputs 2019-11-30 00:00:00
Cid
  • 14,968
  • 4
  • 30
  • 45
  • Thanks for the swift reply, at first glance, this should logically be a good solution, I will test it specially for edge cases and get back to you. Just one thing, was my assumption incorrect? I mean then '-1 month' just means 30 days not dynamically "one month"? – ZeitWert Jan 09 '20 at 09:29