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:

<?php

//Last day of current month.
$lastDayThisMonth = date("Y-m-t");

//Print it out for example purposes.
echo $lastDayThisMonth;

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:

<?php

//Our example date.
//The 4th of February 2014.
$dateString = '2014-02-04';

//Last date of current month.
$lastDateOfMonth = date("Y-m-t", strtotime($dateString));

echo $lastDateOfMonth;

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:

<?php

//Create DateTime object from specified date.
$date = new DateTime('2012-02-01'); 

//Print out your desired result by using
//the format method
echo $date->format('Y-m-t');

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.