Suppose the code is executed on 2018-07-31, how can the output be 2018-07-01?
date("Y-m-d",strtotime("-1 month"))
Okay, although this question seems very confusing, but from the internal logic, it is actually “right”:
Let’s simulate the processing logic for this kind of thing inside date:
1. First do -1 month, then the current is 07-31, and after subtracting one, it will be 06-31.
2. Standardize the date again, because June does not have the 31st, so it is as if 2 o’clock 60 is equal to 3 o’clock, June 31 is equal to July 1
Is the logic very “clear”? We can also manually verify the second step, such as:
var_dump(date("Y-m-d", strtotime("2017-06-31"))); // print 2017-07-01
In other words, as long as the last day of the month and the month is involved, there may be this confusion. We can also easily verify other similar months to confirm this conclusion:
var_dump(date("Y-m-d", strtotime("-1 month", strtotime("2017-03-31")))); // print 2017-03-03 var_dump(date("Y-m-d", strtotime("+1 month", strtotime("2017-08-31")))); // print 2017-10-01 var_dump(date("Y-m-d", strtotime("next month", strtotime("2017-01-31")))); // print 2017-03-03 var_dump(date("Y-m-d", strtotime("last month", strtotime("2017-03-31")))); // print 2017-03-03
So what should we do? Starting from PHP5.3, date has added a series of revised phrases to clarify this problem, that is, “first day of” and “last day of”, that is, you can limit the date to not automatically “Standardization”:
var_dump(date("Y-m-d", strtotime("last day of -1 month", strtotime("2017-03-31")))); // print 2017-02-28 var_dump(date("Y-m-d", strtotime("first day of +1 month", strtotime("2017-08-31")))); // print 2017-09-01 var_dump(date("Y-m-d", strtotime("first day of next month", strtotime("2017-01-31")))); // print 2017-02-01 var_dump(date("Y-m-d", strtotime("last day of last month", strtotime("2017-03-31")))); // print 2017-02-28
If it is a version before 5.3 (does anyone use it?), you can use mktime and the like, and ignore all days. It’s more elegant.Now that I have figured out the internal principles, don’t you panic?