Check if a date is earlier than another date

Asked

Viewed 1,864 times

5

Good morning, I wonder if there is a way to check if one date is earlier or higher than another, in my code there are 2 inputs like date, which send their values to the database, but one date will start something and the other will finish, I would like to make a check before sending to the bank that does not allow the first date to be longer than the second, has to do this?

FORM:

<tr>
    <th>Data de Inicio:</th>
    <td><input type="date" class="form-control input-sm" name="Data_Inicio" required><br></td>
</tr>  
<tr>
    <th>Data de Encerramento:</th>
    <td><input type="date" class="form-control input-sm" name="Data_fim" required><br></td>
</tr>

PHP:

$Data01 = explode("-", $Data_in);
$Data02 = explode("-", $Data_fim);
$Ndata_in = $Data01[0] . '/' . $Data01[1] . '/' . $Data01[2];
$Ndata_fim = $Data02[0] . '/' . $Data02[1] . '/' . $Data02[2];

$sql = 'INSERT INTO walldata VALUES ("' . $Ndata_in . '", "' . $Ndata_fim . '")';
  • You’re doing it the hard way. I’ll try to help you

  • Okay Wallace Thanks :D

3 answers

6


The right way is:

$data1 = new DateTime( '2016-06-06' );
$data2 = new DateTime( '2016-06-15' );

echo ($data1 < $data2) ? "Está Ok!" : "Data de encerramento errada";

In the query you can use only the string of the pure date even in that format 1996-12-10 (aaaa-mm-dd)

  • Okay, thanks but this will serve to check the dates, to know which is valid, ex: $data_in = 19/01/2000 , $data_fim = 18/01/2000, error the closing date should be higher than the starting one, I hope to have explained well :D

  • I didn’t quite understand kk the answer code checks if one date is shorter than the other, where $data1 is the beginning and $data2 is the end. Already to check if a valid date is not necessary, because Html5 does this. If you want to validate if the date is longer than the current date just use $data1 = new DateTime( date() );

  • I understand what you mean thank you

4

Colleague @lvcs already gave a good example of the use of Datetime, but I could not help saying that if the dates are strings in the format already used by Mysql, in the format AAAA-MM-DD, it is unnecessary to instantiate two objects DateTime.

Much simpler and more efficient make the comparison directly:

$data_menor = '2016-06-01';
$data_maior = '2016-02-31';

echo ( $data_menor  < $data_maior ) ? "Está Ok!" : "Data de encerramento errada";


If you want to reverse automatically it’s also simple:

$data_menor = '2016-06-01';
$data_maior = '2016-02-31';

if( $data_menor > $data_maior ) {
   $tmp = $data_maior ;
   $data_maior = $data_menor ;
   $data_menor = $tmp;
}

$sql = 'INSERT INTO walldata VALUES ("' . $data_menor . '", "' . $data_maior . '")';


PS: The above variable exchange is much faster than doing list($x,$y) = array($y,$x);

1

"make a check before sending to the bank that does not allow the first date to be greater than the second"

You can do it two different ways:

  1. Back end - php
  2. Front end - javascript

I usually use javascript to avoid code in php. That said, using JS, there are at least 2 possibilities for this task.

  1. Using pure javascript
  2. Using one of the various JS libraries. I use datepicker jquery.

This application allows multiple date field settings in a very simple way.

I have a code that I use in my applications. It is bi-directional. In the following scenario there is a date to deliver products and a date to relaunch the party. Then the user chooses the expected date to receive the product. When this date is chosen, the date of the feast may only be greater than or equal to the date of arrival. There is also the possibility for the user to choose the date of the party first. So the maximum date of delivery of the product can only be the date of the event.

Hope it helps, try to suit your needs.

    //Validar datas:

    //Quando abre o datapicker seleciona a menor data para ser o dia de hoje now().
    var now = new Date(),
    minDateJS = now.toISOString().substring(0,10);

    //Seleciona a data de entrega do produto.
    //Aplica a data now (hoje) para ser a menor data selecionavel para a entrega do produto
    //Aplica a data de entrega do produto para ser a menor data possivel do evento  
    $('#dt_entregaProd').datepicker({
        dateFormat: 'yy-mm-dd',
        changeMonth: true,
        changeYear: true,
        minDate: minDateJS,
        inline: true,         
        onClose: function( selectedDate ) {//Passa a data selecionada neste objeto para ser a menor data possivel para realizar o evento
          $( "#dt_Event" ).datepicker( "option", "minDate", selectedDate );
        }

    });             


    //Seleciona a data do evento.
    //Evento bidirecional. Se a data do evento for selecionada primeiro, entã a data máxima de entrega do produto será limitada automaticamente
    $('#dt_Event').datepicker({
        dateFormat: 'yy-mm-dd',
        changeMonth: true,
        changeYear: true,
        minDate: minDateJS,
        inline: true, 
        onClose: function( selectedDate ) {
          $( "#dt_entregaProd" ).datepicker( "option", "maxDate", selectedDate );
        }        
     });       

Browser other questions tagged

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