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
Using Zend_Date it's pretty easy:
$date->setDay($date->get(Zend_Date::MONTH_DAYS));
Here is a complete function:
public function get_number_of_days_in_month($month, $year) {
// Using first day of the month, it doesn't really matter
$date = $year."-".$month."-1";
return date("t", strtotime($date));
}
This would output following:
echo get_number_of_days_in_month(2,2014);
Output: 28
There is also the built in PHP function cal_days_in_month()?
"This function will return the number of days in the month of year for the specified calendar." http://php.net/manual/en/function.cal-days-in-month.
echo cal_days_in_month(CAL_GREGORIAN, 11, 2009);
// = 30
I have wrapped it in my date time helper class here
https://github.com/normandqq/Date-Time-Helper
using
$dateLastDay = Model_DTHpr::getLastDayOfTheMonth();
And it is done
$startDate = '2011-12-01';
$endDate = date('Y-m');
while (true) {
try {
$startDateTime = new DateTime($startDate);
$startDateTime->add(new DateInterval('P1M'));
$startDate = $startDateTime->format('Y-m-d');
$endTime = $startDateTime->format('Y-m-t');
echo $startDate . ' => ' . $endTime . PHP_EOL;
if ($startDateTime->format('Y-m') == $endDate) {
break;
}
} catch (Exception $exception) {
var_dump($exception->getMessage());
break;
}
}
After testing many solutions, this works best for me.
$date1 = $year.'-'.$month;
$d = date_create_from_format('Y-m',$date1);
$last_day = date_format($d, 't');