-1 Month does not return to the previous month - PHP

Asked

Viewed 1,019 times

2

Wore the strtotime() to return to the previous month and always take the last day of the previous month, did so:

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

And it was working so far (31-10-2018), instead of going back to 30-09-2018 it showed the day 31-10-2018, apparently the function goes back 30 days and not to "the previous month" as I thought it did. Does anyone know a way out of this situation?

1 answer

6


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

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

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

In your code it is 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: https://3v4l.org/SUHoX

  • When I used the first example you said above, it returned me to the last day of the last month of the last year that PHP can get back kkkk, I think it’s because of the PHP version that I’m required to use is 5.1.6 and he understood differently

  • There have been several changes between PHP 5.0.0 and 5.3.0. Some interpretations of the relative format have changed during this period.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.