How can I get the last day of the month in PHP?
Given:
$a_date = "2009-11-23"
I want 2009-11-30; and given
$a_date = "2009-12-23"
I want 2009-12-31.
How can I get the last day of the month in PHP?
Given:
$a_date = "2009-11-23"
I want 2009-11-30; and given
$a_date = "2009-12-23"
I want 2009-12-31.
t
returns the number of days in the month of a given date (see the docs for date
):
$a_date = "2009-11-23";
echo date("Y-m-t", strtotime($a_date));
You could create a date for the first of the next month, and then use strtotime("-1 day", $firstOfNextMonth)
You can use "t
" in date function to get the number of day in a particular month.
The code will be something like this:
function lastDateOfMonth($Month, $Year=-1) {
if ($Year < 0) $Year = 0+date("Y");
$aMonth = mktime(0, 0, 0, $Month, 1, $Year);
$NumOfDay = 0+date("t", $aMonth);
$LastDayOfMonth = mktime(0, 0, 0, $Month, $NumOfDay, $Year);
return $LastDayOfMonth;
}
for($Month = 1; $Month <= 12; $Month++)
echo date("Y-n-j", lastDateOfMonth($Month))."\n";
The code is self-explained. So hope it helps.