Php function to get the last day of a month

Here is a function that would get the last day of a given month as a date in format Y-m-d. It first adds 1 month to the 1st date of the given month, then subtracts 1 second from the resulting date which brings back to the last date of the given month.

/**
	Last date of a month of a year
	
	@param[in] $month - Integer. Default = Current Month
	@param[in] $year - Integer. Default = Current Year
	
	@return Last date of the month and year in yyyy-mm-dd format
*/
function last_day($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);
}






Last Updated On : 21st November 2012

Subscribe to get updates delivered to your inbox

Leave a comment