Today, when I write the program, suddenly found a long time ago to get the number of days of the function, the classic switch version, but to get the number of days last month, I just put the month-1, I guess it was too sleepy, and then see a kind of creepy feeling, would like to deal with, But I think there are some super convenient way, so I found the following version, made a little change.
Get this month's date:
Copy Code code 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 2014-2 so, $firstday will be 2014-02-01, and then according to $firstday plus one months is 2014-03-01, minus one day is 2014-02-28, It's really convenient to use date () and Strtotime ().
Get date of last month:
Copy Code code 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);
}
Last month's date needs to get a timestamp, and then on the month-1 is OK, super smart Date () will convert 2014-0-1 this thing to 2013-12-01, it's cool.
Get Next month Date:
Copy Code code 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 bit longer because date () is not going to be like 2014-13-01, it will go straight back to 1970, so you need to deal with the December problem, except for the December direct month +1 is OK.
Generally speaking, it is very convenient, the date function is too powerful.