How to get the last days of the month in PHP
I want to get the last days of the current month. This is the code for today's date:
$datee= date("d/m/Y");
4 answers
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 working on ideone. E no repl.it. also I put on GitHub for future reference .
There is also a proper function for this called cal_days_in_month but the first form is more used.
There is still the possibility of catching the first day next month and subtract a day from the date but I also find it unnecessary.
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
Take a look in this project , and you'll find some dated operations you need in addition to other features like masks, validations, etc.
Example to take the last day of the Month:
$minha_data = new DateBr();
$ultimo_dia_do_mes = $minha_data->lastOfMonth();
Quiet just use the date class along with strtotime
.
<?php
$P_Dia_Mes_Atual = date("Y-m-01 00:00:00:00");
$U_Dia_Mes_Atual = date("Y-m-t 00:00:00:00");
$P_Dia_Mes_Anterior = date("Y-m-01 00:00:00:00",strtotime("-1 month"));
$U_Dia_Mes_Anterior = date("Y-m-t 00:00:00:00",strtotime("-1 month"));
print $P_Dia_Mes_Atual;
print $U_Dia_Mes_Atual;
print $P_Dia_Mes_Anterior;
print $U_Dia_Mes_Anterior;