PHP: Get last day of month.

This is a short tutorial on how to get the last day / date of a given month using PHP. In the code snippets below, I will show you how to get the last date of this month, as well as the last day of a month from a specified date.

The key to getting the last date of a month is the letter “t”. When used with PHP’s date function, the letter “t” acts as a format character that returns the number of days that are in a given month.

This month.

The last day of this month:

In the code above, we simply provide PHP’s date function with the format characters “Y-m-t”. If you test it out for yourself, you’ll see that that a YYYY-MM-DD date string is returned and that it looks something like this: “2016-08-31”

From a given date.

The last day of a month – from a given date:

In the example above, we have the date string “2014-02-04”, which is a YYYY-MM-DD date for the 4th of February, 2014. To get the last date of February, 2014, we simply convert the date to a UNIX timestamp using PHP’s strtotime function; before using the resulting timestamp as the second parameter in our date function. If you run the PHP code above, you’ll see that the result is: “2014-02-28”.

If you only want to return the number of days in a given month, then simply omit the “Y” and “m” format characters.

Using the DateTime object.

If you’re looking for an OO interface, then you can also make use of the DateTime object:

Note: If you want to get the last date of the current month, then simply create the DateTime object without passing in a string as the constructor parameter.

Comments

comments