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.

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.

  • Why not just use date("t") to accomplish this through mktime?
    .-= Sven Welzel´s last blog ..Afrigator.com down? =-.

  • Why not just use date("t") to accomplish this through mktime?
    .-= Sven Welzel´s last blog ..Afrigator.com down? =-.

  • Ha ha, that would be because up to now I didn’t know that switch for the date() function existed! So there you go folks, use the ‘t’ switch for date instead. Far, far simpler! :)

  • Ha ha, that would be because up to now I didn’t know that switch for the date() function existed! So there you go folks, use the ‘t’ switch for date instead. Far, far simpler! :)

  • This is very informative, thank you for posting the
    tutorial!

    It’s nice to find a good article. I really enjoy lots of the
    blog posts on your web site.

  • Hairul Azami

    Just simple to get last date of month in year:
    $year             = ‘2011’;$start_date = $year.’-01-01′;$end_date   = date(“Y-m-t”, strtotime($year.’-12-01′));