Because the work needs to get the date of the previous month, next month, and this month, we found the implementation code from the website and shared it to help our friends write programs today, I suddenly found the function to get the number of days of the month written a long time ago, the classic switch version, but when I got the number of days of the previous month, I just took the month-1, it is estimated that it was too difficult at that time, I can see that there is a sense of treasure. I was trying to deal with it again, but I think there must be some super-convenient methods. so I found the following version and made some minor changes.
Get the date of this month:
The code is as follows:
Function getMonth ($ date ){
$ Firstday = date ("Y-m-01", strtotime ($ date ));
$ Lastday = date ("Y-m-d", strtotime ("$ firstday + 1 month-1 day "));
Return array ($ firstday, $ lastday );
}
$ Firstday is the first day of the month. if $ date is like 2014-2, $ firstday will be. Then, add a month based on $ firstday to, and then subtract one day from, it is really convenient to use date () and strtotime.
Get Last Month Date:
The code is as follows:
Function getlastMonthDays ($ date ){
$ Timestamp = strtotime ($ date );
$ Firstday = date ('Y-m-01 ', strtotime (date ('Y', $ timestamp ). '-'. (date ('M', $ timestamp)-1 ). '-01 '));
$ Lastday = date ('Y-m-D', strtotime ("$ firstday + 1 month-1 day "));
Return array ($ firstday, $ lastday );
}
You need to get a timestamp for the last month, and then-1 in the month will be OK. the super intelligent date () will convert 2014-0-1 to, which is so nice.
Obtain the date of next month:
The code is as follows:
Function getNextMonthDays ($ date ){
$ Timestamp = strtotime ($ date );
$ Arr = getdate ($ timestamp );
If ($ arr ['mon'] = 12 ){
$ Year = $ arr ['Year'] + 1;
$ Month = $ arr ['mon']-11;
$ Firstday = $ year. '-0'. $ month.'-01 ';
$ Lastday = date ('Y-m-D', strtotime ("$ firstday + 1 month-1 day "));
} Else {
$ Firstday = date ('Y-m-01 ', strtotime (date ('Y', $ timestamp ). '-'. (date ('M', $ timestamp) + 1 ). '-01 '));
$ Lastday = date ('Y-m-D', strtotime ("$ firstday + 1 month-1 day "));
}
Return array ($ firstday, $ lastday );
}
The code for the next month's date looks a little longer, because date () cannot be converted into something similar to 2014-13-01, and it will return directly to 1970, so we need to deal with the issue of December before, in addition to December, the month + 1 is OK.
In general, it is very convenient. the date function is too powerful.