PHP last day of the month calculation
Tuesday, 15 May 2007
Here’s the easiest way to output the last day of any month using PHP:
function lastday($month = '', $year = '') {
if (empty($month)) {
$month = date('m');
}
if (empty($year)) {
$year = date('Y');
}
$result = strtotime("{$year}-{$month}-01");
$result = strtotime('-1 second', strtotime('+1 month', $result));
return date('Y-m-d', $result);
}
We found it useful for reporting purposes when filtering data purely for the “current” month but by specifying the month and year arguments, you can use it for any month of any year.
Please note that the output is in IS0 8601 international date format. If you need anything else, modify the last line to suit.
|
Great article. Thank you.
I'd have to disagree. The easiest way is this:
$datemk = mktime(23,59,59,date("m"),0,date("Y")); $date = date("Y-m-d", $datemk);$date = date('t');
It will give you the last day of the current month :)
Function wise this is a better method:
Last day of the month has actually been documented on the php manual as its an often requested now.
It's called "Date Validation". Is the date valid? 2/30/2008 or 11/31/2008 for example.