0

Possible Duplicate:
PHP last day of the month

In PHP, I am trying to get the last day of last month. For example, today is December 11 2012. So the date I am then trying to grab is November 30th.

This is what I am currently trying to do:

        //this grabs the last daye of this month
        $current_month = date('Y-m-t',strtotime('today'));

        //this should grab November 30th.
        $last_month = date("F, Y",strtotime($current_month." -1 month ")

Instead of it grabbing November 30th, it is grabbing December 1st. Is seems like "-1 month" simply subtracts 30 days.

How do I properly grab the last day of last month?

Community
  • 1
  • 1
steeped
  • 2,613
  • 5
  • 27
  • 43

3 Answers3

5
$datetime = new DateTime('last day of this month');
echo $datetime->format('F jS');

or

$datetime = new DateTime();
echo $datetime->format('Y-m-t');

The first one allows you to format the output anyway you want to. If you want to use a month that is not the current month you can pass the DateTime constructor a valid date format and then the code will do the rest.

John Conde
  • 217,595
  • 99
  • 455
  • 496
4

cal_days_in_month() is what you want. The last day is the same as the total number of days.

cal_days_in_month (int $calendar,int $month,int $year)

$calendar is typically CAL_GREGORIAN

Send the $month - 1 to the function for the result you want.

3

You can call mktime() with current month/year and 0 as day:

$last_day_of_last_month = mktime(0, 0, 0, date('n'), 0, date('Y'));

It's documented:

day [...] Values less than 1 (including negative values) reference the days in the previous month, so 0 is the last day of the previous month, -1 is the day before that, etc. Values greater than the number of days in the relevant month reference the appropriate day in the following month(s).

Álvaro González
  • 142,137
  • 41
  • 261
  • 360