Date range

1

I am using the HTML date type 5, for the user to provide a date.

<input type="date" name="data-inicial">
<input type="date" name="data-final">

There are two fields: Start date and End date, but the end date must be at most 29 days after the start date. That is, if staff select the start date of 7/23/2018, it has a maximum of 29 days after that date to select the end date.

    
asked by anonymous 23.07.2018 / 18:26

2 answers

3

An example of how it can be done ...

HTML5

<input type='date' id='d1' name='d1' min="">
<input type='date' id='d2' name='d2' min="">

JS (JQuery)

<script>
  $(document).ready(function() {
      $("#d1").change(function () {
        var split = $("#d1").val().split('-');
        var fim = new Date(parseInt(split[0]), parseInt(split[1]), parseInt(split[2]) + 29);
        $("#d2").attr({
           "min" : [fim.getFullYear(), 
                (fim.getMonth() > 9 ? '' : '0') + fim.getMonth(), 
                (fim.getDate() > 9 ? '' : '0') + fim.getDate()]
                .join('-')
        });
      });
  });
</script>
    
23.07.2018 / 19:32
0

Good afternoon friend: D

When you subtract a date from another you get a timestamp simply convert it to the desired format follows practical example:

Explanation:

  • First I get the inputs at the top of the page with document.getElementsByName as it returns an array I get the first one as the search name.

  • Next comes the check method which, in turn, gets the values of each input and creates an instance of the Date .

  • Finally I subtract one date from the other and use Math.abs for if the start is greater than the end it makes the negative difference to positive.

  • Split to 1000.0 to leave in unixtimestamp format

  • And I divide by 86400 to get the difference in days.

  • Finally I check if the difference is greater than 29 if I display a alert () .

  • const dataInicial = document.getElementsByName('data-inicial')[0];
    const dataFinal = document.getElementsByName('data-final')[0];
    
    function checar() {
      const inicio = new Date(dataInicial.value);
      const fim = new Date(dataFinal.value);
      
      const diferenca = Math.abs(inicio - fim) / 1000.0;
      const diferencaEmDias = diferenca/86400;
    
      //
      // Tabela timestamp
      //
      /*    1 Hr      |    3600 Seg        */
      /*    1 Dia     |    86400 Seg       */
      /*    1 Semana  |    604800 Seg      */
      /*    1 Mes     |    2629743 Seg     */
      /*    1 Ano     |    31556926 Seg    */
    
    
      console.log('${diferencaEmDias} dias de diferença');
      
      if (diferencaEmDias > 29) {
        alert('Maior que o limite');
      }
    }
    <input type="date" name="data-inicial">
    <input type="date" name="data-final">
    <button onclick="checar()">DIFERENÇA</button>

    There are libraries that make it easy to work with Dates such as MomentJs

        
    23.07.2018 / 19:01