-1 month does not return to previous month - PHP

1

I used strtotime() to go back to the previous month and always take the last day of the previous month, I used to do this:

$data_teste = date('Y-m-t', strtotime('-1 month'));

And it was going on right up to today (31-10-2018), instead of going back to the 30-09-2018 it showed the day 31-10-2018, apparently the function returns 30 days and not for "the previous month "as I thought she did. Does anyone know a way out of this situation?

    
asked by anonymous 31.10.2018 / 15:33

1 answer

5

When you use relative formats, you must "relativize" the result.

Currently being 31/10/2018 , using -1 month or last month , the date will be 31/09/2018 .

When this date is converted to time, or any other date function, it is interpreted as 01/10/2018 .

In your code it's easy to interpret that you always want the last day of the month, in this case use a more direct approach:

$date_teste = date('Y-m-d', strtotime('last day of last month'));

Or

$date_teste = new DateTime('last day of last month');

See the examples: link

    
31.10.2018 / 15:49