Comparison between month and year

-2

I need to compare only the year and month between two dates, I did it the following way and it works perfectly:

$mes1 = "2018/02";
$mes2 = "2018/03";

if($mes1 > $mes2) {

    echo "Mês 1 é maior que mês 2";

}elseif($mes2 > $mes1) {

    echo "Mês 2 é maior que mês 1";

}

My question is about good practices, comparing just the year and month so this is correct, or would I need to use some feature of php to say that it is a date? my fear is that it starts to give an error in some version of php future.

I do not know what to do, but I do not know what to do.

  

I know there are several posts that might look similar to   but they are not.

    
asked by anonymous 14.10.2018 / 00:22

3 answers

0

Young,

Your solution is not wrong, but PHP has functions ready to streamline and make things transparent for example after dealing with the data by inserting into a MySQL of life ..

I've done an example, I hope it helps:

<?php
   $mes1 = '2001-03-21';
   $mes2 = '2014-05-21';

   $data = new DateTime($mes1); // Data de Nascimento
   $nova_data = $data->diff(new DateTime($mes2));
   $calculo = $nova_data->format('%m');

   $total_meses = $calculo;

   echo $total_meses;

?>
    
14.10.2018 / 01:03
0

The comparison will work in any version, because you are comparing strings, and the most significant character is on the left, while the least significant character is on the right.

Is it a good practice? No, dates are usually converted into integers (timestamp) and then compared for greater flexibility.

    
14.10.2018 / 00:55
0

Concatenate any day on both dates, make them valid dates in PHP and compare with strtotime.

$dia="-01";

$mes1 = "2018/02".$dia;
$mes2 = "2018/03".$dia;


$mes1 = strtotime(str_replace('/', '-', $mes1));

$mes2 = strtotime(str_replace('/', '-', $mes2));



if($mes1 > $mes2) {

    echo "Mês 1 é maior que mês 2";

}elseif($mes2 > $mes1) {

    echo "Mês 2 é maior que mês 1";

}

link

    
14.10.2018 / 02:19