Test equal values (data) in PHP

Asked

Viewed 428 times

3

Hello, I need to test if two dates are equal in PHP (current date x last working day of the month), the two 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 working 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);

For the current date:

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

The two dates show the result 31/07/2014, but I’m not getting equality in the result. If anyone can help.

  • 2

    The variable $ultimo is not in the format with which you are comparing.

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 PHP versions 5.2 or later

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";
  • Recalling that the TimeZone is optional. If not informed, the default server Timezone will be used.

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;

0

Convert the dates to strtotime() and make the comparison, comparison in whole numbers becomes easier.

Browser other questions tagged

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