How to compare dates in PHP?

Asked

Viewed 59,486 times

23

I would like to know which function I use to compare two dates and return to larger.

I have a form for HR registration in which the user will register their professional experiences and the date of entry into employment can not be higher than the date of exit so I need to check this condition and return false.

Someone would have a suggestion how to solve this I found some solutions but the date format was in American standard which does not suit me. Att.

3 answers

37

In order to be able to work with date first of all we have to keep in mind that the standard used is the American standard which requires us to use the Year-Month-Day format (Ex.: 2013-05-22).

In our example we will create a script that compares whether the data1 is greater than or equal to data2 and displaying the corresponding messages.

<?php
 $data1 = '2013-05-21';
 $data2 = '2013-05-22';

 // Comparando as Datas
 if(strtotime($data1) > strtotime($data2))
 {
  echo 'A data 1 é maior que a data 2.';
 }
 elseif(strtotime($data1) == strtotime($data2))
 {
  echo 'A data 1 é igual a data 2.';
 }
 else
 {
  echo 'A data 1 é menor a data 2.';
 }
?>

Note: The strtotime command generates the timestamp of a date in textual format so that we can work with the dates.

Already for the conversion of the pattern can be done this way:

$dataString = '19/03/2013 11:22';
$date = DateTime::createFromFormat('d/m/Y H:i', $dataString);
echo $date->format('Y-m-d H:i:s');

And of course it must be adapted to your need.

  • 3

    face.... just a question.... if the date is in format YYYY-MM-DD Voce need not use strtotime the comparison will already work by simple numerical order.

21

A quick and easy way to do this is by using the class Datetime along with the method createFromFormat.

$timeZone = new DateTimeZone('UTC');

/** Assumido que $dataEntrada e $dataSaida estao em formato dia/mes/ano */
$data1 = DateTime::createFromFormat ('d/m/Y', $dataEntrada, $timeZone);
$data2 = DateTime::createFromFormat ('d/m/Y', $dataSaida, $timeZone);

/** Testa se sao validas */
if (!($data1 instanceof DateTime)) {
  echo 'Data de entrada invalida!!';
}

if (!($data2 instanceof DateTime)) {
  echo 'Data de saida invalida!!';
}

/** Compara as datas normalmente com operadores de comparacao < > = e !=*/
if ($data1 > $data2) {
  echo 'Data de entrada maior que data de saida!';
}

if ($data1 < $data2) {
  echo 'Data de entrada menor que data de saida!';
}

In this example I used the class Datetimezone to ensure that dates are in the same time zone, avoiding scheduling problems.

5

In addition to what Otto has already said, you can do this in a less specific way (which is what I thought you wanted, since you wrote that it did not fit the American standard). If you save the date with dashes or delimiters in the middle of it, just use preg_replace(or any other function that fulfills this) in the string to remove the character that separates year, month and day. If you don’t use go straight to the next step...

After removing the delimiter characters:

<?php
$data_entrada = "01022014";
$dia_entrada = substr($data_entrada, 0, 2);
$mes_entrada = substr($data_entrada, 2, 2);
$ano_entrada = substr($data_entrada, 4, 4);
$data_saida = "01022014";
$dia_saida = substr($data_saida, 0, 2);
$mes_saida = substr($data_saida, 2, 2);
$ano_saida = substr($data_saida, 4, 4);


if ($ano_saida > $ano_entrada) {
    echo "A data de saída é posterior a de entrada";
} elseif ($ano_saida == $ano_entrada) {
// CASO ANO IGUAL
    if ($mes_saida > $mes_entrada) {
        echo "A data de saída é posterior a de entrada";
    } elseif ($mes_saida == $mes_entrada) {
        // INICIO CASO MES IGUAL
       if ($dia_saida > $dia_entrada) {
        echo "A data de saída é posterior a de entrada";
       } elseif ($dia_saida == $dia_entrada) {
        echo "As datas de saída e entrada são  iguais";
} elseif ($dia_saida < $dia_entrada) {
    echo "A data de saída é anterior a de entrada";
} // FIM CASO MES IGUAL
} elseif ($mes_saida < $mes_entrada) {
    echo "A data de saída é anterior a de entrada";
}
// FIM DO CASO ANO IGUAL
} else {
    echo "A data de saída é anterior a de entrada";
}

?>

Note: If necessary, remember to remove blanks after and before the string using trim() or others...

  • 3

    -1 PHP has several ways to work with dates. substr or preg_replace are quite unnecessary in this case.

Browser other questions tagged

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