How do we know the date is the last day of the month?

Asked

Viewed 1,052 times

14

I have a date saved in the database and, before I present 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.

4 answers

14


You can do it using the class PHP Datetime.

Example 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;
    }else{
        return false;
    }
}

Use:

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)

Explanation:

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

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

  • Very good, good idea.

  • 1

    Perfect. Thank you very much

  • 2

    Because it would have the condition of ==, with 3?

  • 2

    Good solution, simple and practical. It would not be enough == ?

  • 3

    @Andrébaill three signs of equals makes the comparison of equal value and type, ie exactly equal (same value and same type).

12

To get the last day of the month just that:

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

Can use gmdate if you prefer. Usually, to be used in loops, use numbers, as obtained by time() is much more effective than instantiating an object for that.

See working on IDEONE.

Using Mysql, for example, this is enough to get the date already in a certain format to work, without making numerous conversions:

SELECT UNIX_TIMESTAMP( data_evento );

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

  • Very good solution with date(), quick and simple

  • @Miguel Almost always pure date() is better and simpler than Datetime in PHP. Then I will improve the answer and show how to convert d/m/Y in unix_timestamp, which is the same format as the date()

8

Another option would be to use the function cal_days_in_month which 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, that "printa" on the screen if the current day is the last day of the month, returned by the function cal_days_in_month

7

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

<?php
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 working

  • 2

    It’s really funny. Guilhermenascimento and I call this "talking php"

Browser other questions tagged

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