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_dat
Nowadays DateTime does this quite conveniently if you have month and year you can
$date = new DateTime('last day of '.$year.'-'.$month);
From another DateTime object that would be
$date = new DateTime('last day of '.$otherdate->format('Y-m'));
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.
What is wrong - The most elegant for me is using DateTime
I wonder I do not see DateTime::createFromFormat, one-liner
$lastDay = \DateTime::createFromFormat("Y-m-d", "2009-11-23")->format("Y-m-t");
There are ways to get last day of month.
//to get last day of current month
echo date("t", strtotime('now'));
//to get last day from specific date
$date = "2014-07-24";
echo date("t", strtotime($date));
//to get last day from specific date by calendar
$date = "2014-07-24";
$dateArr=explode('-',$date);
echo cal_days_in_month(CAL_GREGORIAN, $dateArr[1], $dateArr[0]);