PHP 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 PHP.
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));
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.