Today, I saw a small case on weibo. The command line is as follows:
The code is as follows: |
Copy code |
Php-r "echo date ('Y/M', strtotime ('-2 months'). \" \ n \";" |
The output result is as follows:
2013/03
If you change the command line to the following:
The code is as follows: |
Copy code |
Php-r "echo date ('Y/M', strtotime ('-3 months'). \" \ n \";" |
The output result is as follows:
2013/03
This is strange. How can we use the same year and month as three months ago? Let's look at the following command line:
The code is as follows: |
Copy code |
Php-r "echo date ('Y/M', strtotime ('-3 months', strtotime ('2017/28 & prime ;))). \ "\ n \";" |
The output result is as follows:
2013/02
If you modify the command behavior as follows:
The code is as follows: |
Copy code |
Php-r "echo date ('Y/M', strtotime ('-3 months', strtotime ('2017/29 & prime ;))). \ "\ n \";" |
The output result is as follows:
2013/03
The following is the same as the expected result. Now let's talk about why the strange pitfall came into being.
In strtotime, the months and month are 30 days. When using them, you must consider 31 days and February. Therefore, if you do not consider this special case, the flexibility at the beginning may occur on the 31st of each month or at a time point related to the month. This is a pitfall of strtotime. To be cautious, if you don't need it, try not to use it.
PS: all of the preceding examples are executed in the 64-bit Debian 6 system and run in the command line mode. The execution time is 2013-05-30.
Inaccurate last month and next month
There are several methods to help us achieve the expected results, for example, I want to return the month of the previous month:
The code is as follows: |
Copy code |
Echo date ('m Y', strtotime ('Midnight first day of-1 month ')); Or: Echo date ('m Y', strtotime (date ('Y-m-01 ')-86400 ); |
Below are other purposes:
The code is as follows: |
Copy code |
Strtotime ('first day of last month '); Strtotime ('Last day of last month '); Strtotime ('first of last week '); Strtotime ('first of this week '); Strtotime ('this week midnight '); // returns Monday midnight of this week Strtotime ('last week midnight '); // returns Monday midnight of last week Strtotime ('last week Sunday midnight '); // returns Sunday midnight of this week Strtotime ('-2 weeks Sunday midnight'); // returns Sunday midnight of last week <? Php Date_default_timezone_set ('Asia/Shanghai '); $ First_day_of_month = date ('Y-M', time (). '- 01 00:00:01 '; $ T = strtotime ($ first_day_of_month ); Print_r (array ( Date ('Y-mmonth', $ t ), Date ('Y-mmonth', strtotime ('-1 month', $ t )), Date ('Y-mmonth', strtotime ('-2 month', $ t )), )); ?> |