Simplify your business
Monday, 13 October 2008 11:07 pm

PHP last day of the month calculation

Tuesday, 15 May 2007  

Here’s the easiest way to output the last day of any month using PHP:

function lastday($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);
}

We found it useful for reporting purposes when filtering data purely for the “current” month but by specifying the month and year arguments, you can use it for any month of any year.

Please note that the output is in IS0 8601 international date format. If you need anything else, modify the last line to suit.

Posted in PHP, Tips by Ivan
Blinklist icon Del.iocio.us icon Furl icon Reddit icon Technorati icon Yahoo! icon

 five comments:

  1. Referate - Friday, 18 January 2008 9:16 pm  

    Great article. Thank you.

  2. J - Tuesday, 3 June 2008 9:05 am  

    I'd have to disagree. The easiest way is this:

    $datemk = mktime(23,59,59,date("m"),0,date("Y")); $date = date("Y-m-d", $datemk);

  3. Vitor S. - Thursday, 31 July 2008 1:20 am  

    $date = date('t');

    It will give you the last day of the current month :)

  4. CJ - Tuesday, 23 September 2008 7:51 pm  

    Function wise this is a better method:

    function lastday($month = '', $year = '') {
       if (empty($month)) {
          $month = date('m');
       }
       if (empty($year)) {
          $year = date('Y');
       }
       return date('Y-m-d', mktime(0, 0, 0, $month, 0, $year));
    }
    

    Last day of the month has actually been documented on the php manual as its an often requested now.

  5. Jodo Kast - Saturday, 27 September 2008 12:22 am  

    It's called "Date Validation". Is the date valid? 2/30/2008 or 11/31/2008 for example.


Got something to say?

To protect your privacy, your email address will not be displayed.





Some basic rules for commenting:

  • Watch your language.
  • Keep comments on-topic and relevant.
  • You can use basic XHTML tags for formatting and linking but not bbcode.
  • Comments are moderated, so don't double post if your comment doesn't appear immediately.
  • Please proof-read your comments for spelling and grammar mistakes.
  • Watch your language.