PHP, last month
Strtotime has a small problem
The code is as follows: |
Copy code |
> Php-r "echo date ('ymd000000 & prime;, strtotime ('-1 month', strtotime ('2017 & prime ;)));" 20130701000000 # > Php-r "echo date ('ymd000000 & prime;, strtotime ('-1 month', strtotime ('2017 & prime ;)));" 20130701000000 # |
After searching, the following methods are more accurate.
The code is as follows: |
Copy code |
$ Time = strtotime ("2011-03-31 "); |
The mktime function can obtain the timestamp of a date:
Int mktime ([int $ hour [, int $ minute [, int $ second [, int $ month [, int $ day [, int $ year [, int $ is_dst])
Returns the Unix timestamp based on the given parameters. The timestamp is a long integer that contains the number of seconds from the Unix epoch (January 1 1970 00:00:00 GMT) to the given time.
The parameter can be omitted from the right to the left. Any omitted parameter is set to the current value of the local date and time.
So we can use it to calculate
The code is as follows: |
Copy code |
Function last_month_day ($ time ){ $ Strtime = mktime (date ('H', $ time), date ('I', $ time), date ('s', $ time ), date ('M', $ time)-1, date ('D', $ time), date ('Y', $ time )); Echo date ('Y-m-D', $ strtime ); } Last_month_day (strtotime ("2012-03-31 ")); |
The output result is. The output is ???? Are there any February dummies? No. Is there a 30th number? Are there on the 29th ?.. This...
PHP handles this situation for us. It will take several more days to calculate it by the next month.
The last day of June is February 2012, so the 31st day is two days later than that of June 29, so PHP will be added to the next month to handle the problem on May 29.
I almost forgot. How can I calculate the day of the week ?? You don't have to worry about it. PHP is ready for us.
Date ('W', $ strtime); the day of the week is the day of the week.
Example
The code is as follows: |
Copy code |
/** * Calculate the current day of the previous month. If the previous month does not have today, return the last day of the previous month. * @ Param type $ time * @ Return type */ Function last_month_today ($ time ){ $ Last_month_time = mktime (date ("G", $ time), date ("I", $ time ), Date ("s", $ time), date ("n", $ time), 0, date ("Y", $ time )); $ Last_month_t = date ("t", $ last_month_time ); If ($ last_month_t <date ("j", $ time )){ Return date ("Y-m-t H: I: s", $ last_month_time ); } Return date ("Y-m", $ last_month_time). "-d", $ time ); } Echo last_month_today ($ time ); |