Test equality of values (date) in PHP

3

Hello, I need to test if two dates are the same in PHP (current date vs. last day of the month), both are strings, but I'm not getting the result using the following code:

 if(strcmp($ultimo, $hoje) == 0)
     echo "<br><br>As duas datas são iguais";
 else
     echo "<br><br>As duas datas são diferentes"; 

The calculation for the last business day is as follows:

 $mes = 07;
 $ano = 2014;
 $dias = cal_days_in_month(CAL_GREGORIAN, $mes, $ano);
 $ultimo = mktime(0, 0, 0, $mes, $dias, $ano); 
 $dia = date("j", $ultimo);
 $dia_semana = date("w", $ultimo);
 if($dia_semana == 0){
   $dia--;
   $dia--;
 }
 if($dia_semana == 6)
   $dia--;
 $ultimo = (string)mktime(0, 0, 0, $mes, $dia, $ano);

To the current date:

$hoje= date("d/m/Y"); 

Both dates show the 07/31/2014 result, but I'm not getting equal results. If anyone can help.

    
asked by anonymous 31.07.2014 / 23:00

3 answers

2

Using date ()

<?php
 date_default_timezone_set('America/Sao_Paulo');
 $mes = 07;
 $ano = 2014;
 $dias = cal_days_in_month(CAL_GREGORIAN, $mes, $ano);
 $ultimo = mktime(0, 0, 0, $mes, $dias, $ano); 
 $dia = date("j", $ultimo);
 $dia_semana = date("w", $ultimo);
 if($dia_semana == 0){
   $dia--;
   $dia--;
 }
 if($dia_semana == 6)
   $dia--;
 //repare que precisa-se de converter o mktime para date()
 $ultimo = date("d/m/Y",mktime(0, 0, 0, $mes, $dia, $ano));
 $hoje= date("d/m/Y"); 
 if ($ultimo==$hoje)
     echo "verdadeiro";
 else
     echo "falso";

For versions of PHP equal to or later than 5.2

DateTime:

$timezone = new DateTimeZone('America/Edmonton');
 //...
$ultimo = DateTime::createFromFormat('j-M-Y', '$dia-$mes-$ano',$timezone);
$hoje=  new DateTime(null, $timezone);
if ($ultimo==$hoje)
    echo "verdadeiro";
else
    echo "falso";
    
31.07.2014 / 23:32
0

Convert dates to strtotime () and compare, making comparison in whole numbers easier.

    
01.08.2014 / 04:22
0

You can use the strtotime function to generate an integer and then compare, see:

$dateIni   =   '01/08/2014';

$dateFim   =   '30/08/2014';

echo strtotime($dateIni)  ==  strtotime($dateFim) ? true : false;
    
02.08.2014 / 04:58