Get the Last Day of a Month using PHP CodeUnit 27 MAR 2010

Picked this cool little PHP function to calculate and return the last day of a month for any year off the always informative lutrov interactive website the other day, and posted it here for future reference – because that’s just how I roll! ;)

Anyway, here goes:

function lastday($month = '', $year = '',$format = 'Y-m-d') {
   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($format, $result);
}

As you can see, usage is a simple matter of calling lastday() and feeding it the year and month you want it to return the last day for, though if you leave these two parameters out, it will simply return you the last date of the current month – all in a handy ISO 8601 formatting.

Useful.

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.