How to add the amount of days with jQuery

Asked

Viewed 358 times

1

I’m trying to manipulate dates with jQuery. The idea is this:

The user informs the Data_vencimento and the type (in radio button), whether the salary is weekly, fortnightly, monthly or informed.

In the input informed, the user will enter the number of days (for example, 20 days) so that jQuery can calculate the salaries.

Example:

  1. User reports due date: 14/11/2018;
  2. User selects the weekly salary;
  3. jQuery calculates and fills the value of input #dt_venc1 with the date 21/11/2018. (14 + 7).

Only that the alert(dtVenc1) returns a NaN.

How do you manipulate dates with jQuery? It seems that manipulating dates with PHP is much easier. But with jQuery, it would be independent of the language used.

$(document).ready( function () {
    $('#data_vencimento').on('blur', function() {
        alert('Usuário utilizando o input "DATA_VENCIMENTO"');
        var dtVenc = new Date();
        var dtVenc1 = new Date();
        dtVenc = $('#data_vencimento').val();
        dtVenc1 = dtVenc1.setDate(dtVenc1 + 7);
        alert(dtVenc);
        alert(dtVenc1);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
     <div class="form-group col-md-2">
          <label class="control-label" for="data_vencimento">Data Vencimento *</label>
          <input type="text" class="form-control datepicker required" name="data_vencimento" id="data_vencimento">
     </div>

     <div class="form-group col-md-2">
          <label class="control-label" for="data_prorrogacao">Data Prorrogacao</label>
          <input type="text" class="form-control datepicker" name="data_prorrogacao" id="data_prorrogacao">
     </div>
</div>

<div class="row">
     <div class="form-check form-check-radio form-check-inline">
          <label class="form-check-label" >Tipo de Parcelamento:</label>
          	<input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio1" value="SEMANAL"> Semanal
          	<span class="circle">
                	<span class="check"></span>
          	</span>
          </label>
     </div>
     <div class="form-check form-check-radio form-check-inline">
          <label class="form-check-label">
                <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio2" value="QUINZENAL" checked="checked"> Quinzenal
                     <span class="circle">
                           <span class="check"></span>
                     </span>
          </label>
     </div>
          <div class="form-check form-check-radio form-check-inline">
               <label class="form-check-label">
                     <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio3" value="MENSAL" checked="checked"> Mensal
                            <span class="circle">
                                  <span class="check"></span>
                            </span>
               </label>
     </div>
     <div class="form-check form-check-radio form-check-inline">
          <label class="form-check-label">
               <input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio4" value="INFORMADO"> Informado
                   <span class="circle">
                         <span class="check"></span>
                   </span>
          </label>                           
     </div>
     <div class="col-md-2">
          <div class="form-group has-label">
               <label class="bmd-label-floating" for="dias">Qtd. dias</label>
               <input class="numero form-control" type="text" name="dias" size="03" 
                      id="dias">
          </div>
     </div>
</div>

4 answers

1

You almost got it right..

instead of using:

dtVenc1 = dtVenc1.setDate(dtVenc1 + 7);

Try:

dtVenc1 = dtVenc1.setDate(dtVenc1.getDate() + 7);

1

I would use the Momentjs library to work with dates/times, follow the link:

https://momentjs.com/

In my opinion the best solution for complex calculations using these formats.

  • 1

    Thanks, I’ll take a look at that library.

1

Something seems strange, O usuário informa a Data_vencimento.

I believe that the due date should be calculated from the current date!

so this is how it follows.

The date should be read-only, but it could also be hidden, because the expiration date is from the current date and we all know this.

//pego a data atual para colocar automaticamente no campo data
var today = new Date();
document.getElementById("data_vencimento").value =('0' + today.getDate()).slice(-2) + '/' + ('0' + (today.getMonth() + 1)).slice(-2) + '/' + today.getFullYear();

$(document).ready( function () {

 $("button").click(function(){

 // Tratamento das Variaveis.
        var txtData = $('#data_vencimento').val();
        /*##### se selecionar o input radio com valor = INFORMADO pega o valor do campo dias, caso contrario o valor do input radio selecionado ##### */
        if($('input[type="radio"]:checked').val()=="INFORMADO"){
           var DiasAdd = $("#dias").val();
        }else{
           var DiasAdd = $('input[type="radio"]:checked').val();
        }
       /*############################################################## */

 // Aqui vem quantos dias você quer adicionar a data
        var d = new Date();
            // Aqui eu "mudo" a configuração de datas.
            // Crio um obj Date e pego o campo txtData e 
            // "recorto" ela com o split("/") e depois dou um
            // reverse() para deixar ela em padrão americanos YYYY/MM/DD
            // e logo em seguida eu coloco as barras "/" com o join("/")
            // depois, em milisegundos, eu multiplico um dia (86400000 milisegundos)
            // pelo número de dias que quero somar a txtData.
         d.setTime(Date.parse(txtData.split("/").reverse().join("/"))+(86400000*(DiasAdd)))
        
        // Crio a var da DataFinal            
        var DataFinal;

        // Aqui comparo o dia no objeto d.getDate() e vejo se é menor que dia 10.            
        if(d.getDate() < 10)
        {
            // Se o dia for menor que 10 eu coloca o zero no inicio
            // e depois transformo em string com o toString()
            // para o zero ser reconhecido como uma string e não
            // como um número.
            DataFinal = "0"+d.getDate().toString();
        }
        else
        {    
            // Aqui a mesma coisa, porém se a data for maior do que 10
            // não tenho necessidade de colocar um zero na frente.
            DataFinal = d.getDate().toString();    
        }
        
        // Aqui, já com a soma do mês, vejo se é menor do que 10
        // se for coloco o zero ou não.
        if((d.getMonth()+1) < 10){
            DataFinal += "/0"+(d.getMonth()+1).toString()+"/"+d.getFullYear().toString();
        }
        else
        {
            DataFinal += "/"+((d.getMonth()+1).toString())+"/"+d.getFullYear().toString();
        }
        console.log(DataFinal)

    });
});




       
function adicionarDiasData(dias){
  var hoje        = new Date();
  var dataVenc    = new Date(hoje.getTime() + (dias * 24 * 60 * 60 * 1000));
  return dataVenc.getDate() + "/" + (dataVenc.getMonth() + 1) + "/" + dataVenc.getFullYear();
}
 
var novaData = adicionarDiasData(5);
console.log(novaData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
     <div class="form-group col-md-2">
          <label class="control-label" for="data_vencimento">Data</label>
          <input type="text" class="form-control datepicker required show-pwd" name="data_vencimento" id="data_vencimento">
     </div>

     <div class="form-group col-md-2">
          <label class="control-label" for="data_prorrogacao">Data Prorrogacao</label>
          <input type="text" class="form-control datepicker show-pwd" name="data_prorrogacao" id="data_prorrogacao">
     </div>
</div>

<div class="row">
     <div class="form-check form-check-radio form-check-inline">
          <label class="form-check-label" >Tipo de Parcelamento:</label>
            <input class="form-check-input show-pwd" type="radio" name="inlineRadioOptions" id="inlineRadio1" value="7"> Semanal
            <span class="circle">
                    <span class="check"></span>
            </span>
          </label>
     </div>
     <div class="form-check form-check-radio form-check-inline">
          <label class="form-check-label">
                <input class="form-check-input show-pwd" type="radio" name="inlineRadioOptions" id="inlineRadio2" value="15"> Quinzenal
                     <span class="circle">
                           <span class="check"></span>
                     </span>
          </label>
     </div>
          <div class="form-check form-check-radio form-check-inline">
               <label class="form-check-label">
                     <input class="form-check-input show-pwd" type="radio" name="inlineRadioOptions" id="inlineRadio3" value="30"> Mensal
                            <span class="circle">
                                  <span class="check"></span>
                            </span>
               </label>
     </div>
     <div class="form-check form-check-radio form-check-inline">
          <label class="form-check-label">
               <input class="form-check-input show-pwd" type="radio" name="inlineRadioOptions" id="inlineRadio4" value="INFORMADO"> Informado
                   <span class="circle">
                         <span class="check"></span>
                   </span>
          </label>                           
     </div>
     <div class="col-md-2">
          <div class="form-group has-label">
               <label class="bmd-label-floating" for="dias">Qtd. dias</label>
               <input class="numero form-control  show-pwd" type="text" name="dias" size="03" 
                      id="dias">
          </div>
     </div>
</div>
<button>Data Vencimento</button>

0

errors are the use of the same variable in the calculation dtVenc1 and the lack of getDate() without getDate() its variable is just a string and its sum will result in something like Mon Nov 19 2018 18:02:09 GMT+0300 (GMT+03:00)7 a 7 at the end of the text.

If you use:

dtVenc1.setDate(dtVenc.getDate() + 7);

you will have that value: Mon Nov 19 2018 18:02:09 GMT+0300 (GMT+03:00)

if use

dtVenc1 = dtVenc1.setDate(dtVenc.getDate() + 7);

you will have that value: 1542639729006

  • But does getDate() not bring me the current date? I would like the user to inform a date and Jquery to pick that date and add, for example, 7 days to it, example:

  • 25/11/2018 + 7 = 02/12/2018

  • @Ivan the current date is Date.now(), getDate() is the value the user chooses in caledario.

Browser other questions tagged

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