One day, encounter a problem, ask for one months of today. At first we used the Strtotime ("-1 month") function to evaluate the problem, and the month with different months was wrong. For example: 2011-03-31, the result is 2011-03-03. Let's look at how to solve the problem first. At this point, think of PHP has a mktime function, so I wrote the following code:
Copy CodeThe code is 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 results are found to be the same as the strtotime.
Or based on this function, since it is not possible to manipulate the month directly, we start with the day, get one months, and then use date splicing data. The following code:
Copy CodeThe code is as follows:
$time = Strtotime ("2011-03-31");
/**
* Calculated last one months of today
* @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 now there is another problem, there is no 2011-02-31 such a date, how to do? The demand now is for such a date to show the last day of the month. The following code:
Copy CodeThe code is as follows:
$time = Strtotime ("2011-03-31");
/**
* Calculated for one months today, if not today, then return to 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). The "-D" piece of code. In the process of writing code, if you write "Y". Date ("M", $last _month_time). "-D" has problems over the years. This is still in the writing of this article found.
In addition to this method, you can also first calculate the date and then stitching the string, here is the pure string operation.
http://www.bkjia.com/PHPjc/327118.html www.bkjia.com true http://www.bkjia.com/PHPjc/327118.html techarticle one day, encounter a problem, ask for one months of today. At first we used Strtotime ("-1 month") function evaluation, found that there is a problem, month-length different months of the calculation of the knot ...