Reputation: 49
With this code:
echo strtotime("2018-03-31 -1 month");
PHP returns date 3rd of March 2018, and this is pretty strange, is this eternal bug of strtotime? are there some libraries for php which provide more intuitive result?
Upvotes: 2
Views: 69
Reputation: 17417
It's not a bug, but it's not exactly intuitive.
2018-03-31 minus one month is the 31st of February, which doesn't exist. PHP's implementation of strtotime
deals with any "out of range" dates like these by moving into the next month by the relevant number of days, e.g.
echo date('Y-m-d', strtotime('April 31'));
// 2018-05-01
Using the term -1 month in strtotime
means jumping back to the same date in the previous month, then performing any necessary adjustments as above. For March 31st, you end up on March 3rd. You'd see the same thing if you used +1 month on January 31st.
Depending on exactly what you actually want to happen in this case, some of the answers to this question might be useful: PHP: Adding months to a date, while not exceeding the last day of the month
Upvotes: 3