Get last date of this month in php

February 6th, 2011 § 3 comments

This tutorial helps you to find last date of the month. It’s really easy to find it with “date” and “strtotime” functions.

It is a simple as

Last date of this month

echo date("Y-m-d",strtotime("+1 month -1 second",strtotime(date("Y-m-1"))));

Last date of next month

echo date("Y-m-d",strtotime("+2 month -1 second",strtotime(date("Y-m-1"))));

Last date of previous month

echo date("Y-m-d",strtotime("-1 second",strtotime(date("Y-m-1"))));

The logic behind this is quite simple. Any way the first date of every month will be “1” .We only have a confusion on the last date ie., whether it will be 28,29,30 or 31.

So first we will get the first date of this month by `date(“Y-m-1”)`. For eg. which result us `2011-02-01`.With the help of `strtotime` function i can convert the date into Unix time stamp and with the help of the same function i can add 1 month to it. `strtotime(“+1 month”,strtotime(date(“Y-m-1”))));`. So now it return the Unix time stamp corresponding to  `2011-03-01`. Subtracting a second from this will result you the last date of this month.

Happy coding.

Revath S Kumar [RSK]

- Rubyist / JavaScripter - Yeoman Team member - Open source enthusiast - Blogger @ PHPRepo and http://blog.revathskumar.com - Coder @ Whatznear - Google fanboy - jQuery lover

More Posts - Website - Twitter - Facebook - LinkedIn - Pinterest - Google Plus - YouTube

Tagged ,

  • Pingback: Get last date of this month in php « PHP Repo()

  • Sayuj O

    For me the code does not works. I get the expected result when I interchange a brace [‘)’].

    These codes give me the correct result instead:
    echo date(“Y-m-d”,strtotime(“+1 month -1 second”, strtotime(date(“Y-m-1”))));
    echo date(“Y-m-d”,strtotime(“+2 month -1 second”, strtotime(date(“Y-m-1”))));
    echo date(“Y-m-d”,strtotime(“-1 second”, strtotime(date(“Y-m-1”))));

    • RSK

      Sayuj,
      thankz for the correction. corrected in the post 🙂