How to get the last days of the month in PHP

Asked

Viewed 11,103 times

10

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

13


See the existing formatting parameters in the function date().

The 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");

Behold working in the ideone. And in the repl it.. Also put on the 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 also the possibility to take the first day of next month and subtract a day from the date but also find unnecessary.

6

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

2

Take a look in this project, and you’ll find some date 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();
  • 1

    Justifying my negative: Using a library when you already have it natively would be a waste of resource.

1

Quiet just use the date class along with the 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;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.