How do I know if the date is the last day of the month?


I have a date saved in the database, and before I show it on the grid, I need to know if it's the last day of the month.

I need this information to present it in a different color.

asked by anonymous 18.08.2016 / 02:03

4 answers


You can do this by using the PHP DateTime class .

Sample function:

function ultimoDia($data){
    $formato = 'd/m/Y'; // define o formato de entrada para dd/mm/yyyy
    $dt = DateTime::createFromFormat($formato, $data); // define data desejada
    if($dt->format('t') === $dt->format('d')){
        return true;
        return false;


var_dump(ultimoDia('17/08/2016')); // retorna bool(false)
var_dump(ultimoDia('30/08/2016')); // retorna bool(false)
var_dump(ultimoDia('31/08/2016')); // retorna bool(true)


$dt->format('t') returns the number of days in the month of the date referenced in the object

$dt->format('d') returns the date day referenced in the object

18.08.2016 / 02:13

To get the last day of the month, this is enough:

date("t", $data) == date("d", $data )

You can use gmdate if you prefer. Usually, to use loops , using numbers as obtained by time() is much more effective than instantiating an object for that.

See working at IDEONE .

Using MySQL, for example, this is enough to get the date already in the right format to work without doing a lot of conversions:


The returned value is ready to use in date( ..., $data ) .

18.08.2016 / 02:30

Another option would be to use the cal_days_in_month function that returns the number of days of the month and year reported:

$days = cal_days_in_month(CAL_GREGORIAN, 8, 2016); // Retorna 31
echo (date('d') == $days)? 'Último dia':'';

The comparison is a simple Ternary Operator , which "printa" on the screen if the current day is the last day of the month, returned by the function cal_days_in_month

18.08.2016 / 02:43

A funnier way to do with relative format 'last day of' ;)

function isLastDay($day)
    return date( 'd', strtotime( $day ) ) == date( 'd', strtotime( 'last day of ' . date( 'M Y' , strtotime( $day ) ) ) );

isLastDay("30-06-1984"); //retorna true

See it working

18.08.2016 / 02:59