PHP has already built-in functions that will help in getting the last date of a given month.
strtotime functions are most useful in this scenario, though it’s well known and documented that
strtotime will not work accurately or give correct results after year 2038. However,
strtotime is awesome for converting dates.
Both functions use the format
t which according to the official manual returns the number of days in the month of a given date. Note the key to getting the last day of the month is the letter
t which returns the number of days in a given month.
DateTime to get the last date of the month
This is the best method to use to get the last date of a month both with future and past dates. The parameters passed in the
format() function is -
t. These constants are defined in
A full numeric representation of a year, 4 digits is represented by letter
Y, for example,
2020. Numeric representation of a month, with leading zeros, is by letter
m this is from
12. And the number of days in the given month is represented by letter
This is the best option if the
PHP version used is after
$L = new DateTime( '2020-02-01' ); echo $L->format( 'Y-m-t' );
The code above supplies the
DateTime function with a date and using the format characters
Y-m-t to get the last date of the month on the date supplied.
strtotime() to get last date of month
strtotime() is the best option for PHP version before 5.2.
$date = "2020-01-15"; echo date("Y-m-t", strtotime($date));