How to get the last days of the month in PHP

4

I want to get the last months of the month from today's date. Here is the code for today's date:

$datee= date("d/m/Y");
    
asked by anonymous 29.10.2014 / 23:27

3 answers

7

See the formatting parameters in the date function .

t is what determines the last day of the month.

echo date("Y-m-t", strtotime("2014-10-29")) . "\n";
echo date("Y-m-t") . "\n"; //data de hoje
echo date("t");

See running on ideone . And no Coding Ground . Also put it on GitHub for future reference .

There is also a proper function for this called cal_days_in_month but the first form is most often used.

There is still the possibility to pick up the first day of the next month and subtract one day from the date but I also find it unnecessary.

    
29.10.2014 / 23:31
4

Another option is to do:

$date = new DateTime('now');
$date->modify('last day of this month');
echo $date->format('d'); // somente o dia
echo PHP_EOL;
echo $date->format('d/m'); //dia e mês
echo PHP_EOL;
echo $date->format('d/m/Y'); //dia mês e ano

Ideone Example

    
30.10.2014 / 00:06
2

Take a look in this project , and you'll find some date operations you need as well as other features like masks, validations, etc.

Example to pick up the last day of the month:

$minha_data = new DateBr();
$ultimo_dia_do_mes = $minha_data->lastOfMonth();
    
30.10.2014 / 13:07