One day, meet a problem, ask for one months of today. At first we used the Strtotime ("-1 month") function to evaluate, and found that there was a problem, the month length of the month is not the same as the calculation results are incorrect. For example: 2011-03-31, the result is 2011-03-03. Let's first look at what the problem is and how to solve it. At this point, think of PHP has a mktime function, so I wrote the following code:
Copy Code code as follows:
echo Date ("Y-m-d h:i:s", Mktime (Date ("G", $time), date ("I", $time),
Date ("S", $time), date ("n", $time)-1, Date ("J", $time), date ("Y", $time));
When executed, the result is the same as that of the strtotime.
Or based on this function, since you can't directly manipulate the month, we start with the day, get one months, and then use date to splice the data. The following code:
Copy Code code as follows:
$time = Strtotime ("2011-03-31");
/**
* Calculated today for one months
* @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),-1, date ("Y", $time));
Return Date (date ("Y-m", $last _month_time). "-D h:i:s", $time);
}
echo Last_month_today ($time);
But then there is another problem, there is no 2011-02-31 such a date, how to do? Now the requirement is for such a date to display the last day of the month. The following code:
Copy Code code as follows:
$time = Strtotime ("2011-03-31");
/**
* Calculate one months of today, if not today, return to the last day of one months
* @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 (date ("Y-m", $last _month_time). "-D", $time);
}
echo Last_month_today ($time);
One thing to note here: Date ("Y-m", $last _month_time). "-D" code. In the process of writing code, if you write "Y." Date ("M", $last _month_time). "-D" is problematic over a span of years. This is still found in writing this article.
In addition to this method, you can also calculate the date of the year and then splicing string, here is the pure string operation.