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
I am using strtotime with cal_days_in_month as following:
$date_at_last_of_month=date('Y-m-d', strtotime('2020-4-1
+'.(cal_days_in_month(CAL_GREGORIAN,4,2020)-1).' day'));
You can find last day of the month several ways. But simply you can do this using PHP strtotime() and date() function.I'd imagine your final code would look something like this:
$a_date = "2009-11-23";
echo date('Y-m-t',strtotime($a_date));
Live Demo
But If you are using PHP >= 5.2 I strongly suggest you use the new DateTime object. For example like below:
$a_date = "2009-11-23";
$date = new DateTime($a_date);
$date->modify('last day of this month');
echo $date->format('Y-m-d');
Live Demo
Also, you can solve this using your own function like below:
/**
* Last date of a month of a year
*
* @param[in] $date - Integer. Default = Current Month
*
* @return Last date of the month and year in yyyy-mm-dd format
*/
function last_day_of_the_month($date = '')
{
$month = date('m', strtotime($date));
$year = date('Y', strtotime($date));
$result = strtotime("{$year}-{$month}-01");
$result = strtotime('-1 second', strtotime('+1 month', $result));
return date('Y-m-d', $result);
}
$a_date = "2009-11-23";
echo last_day_of_the_month($a_date);
You could create a date for the first of the next month, and then use strtotime("-1 day", $firstOfNextMonth)
Try this , if you are using PHP 5.3+,
$a_date = "2009-11-23";
$date = new DateTime($a_date);
$date->modify('last day of this month');
echo $date->format('Y-m-d');
For finding next month last date, modify as follows,
$date->modify('last day of 1 month');
echo $date->format('Y-m-d');
and so on..
I am late but there are a handful of easy ways to do this as mentioned:
$days = date("t");
$days = cal_days_in_month(CAL_GREGORIAN, date('m'), date('Y'));
$days = date("j",mktime (date("H"),date("i"),date("s"),(date("n")+1),0,date("Y")));
Using mktime() is my go to for complete control over all aspects of time... I.E.
echo "<br> ".date("Y-n-j",mktime (date("H"),date("i"),date("s"),(11+1),0,2009));
Setting the day to 0 and moving your month up 1 will give you the last day of the previous month. 0 and negative numbers have the similar affect in the different arguements. PHP: mktime - Manual
As a few have said strtotime isn't the most solid way to go and little if none are as easily versatile.
You can also use it with datetime
$date = new \DateTime();
$nbrDay = $date->format('t');
$lastDay = $date->format('Y-m-t');