how to add days in javascript date

Asked

Viewed 57 times

0

Hello, I’m trying to create a form to add days on the date to calculate the date of departure of the client but when I sum the formularies in a strange way and not give me the supposed date ie add 5 days completely changes the date of departure and not only in days

<div class="form-group col-md-3">
  <label for="data_permanencia">Days to stay</label>
  <input type="text" class="form-control" name="data_permanecia" onchange="setSaida()" autocomplete="off" id="data_permanecia" placeholder="Dias">
</div>
<div class="form-row">
  <div class="form-group col-md-3">
    <label for="inputCity">Starting Date</label>
    <input type="text" class="form-control" id="data_entrada" name="data_entrada">
  </div>
  <div class="form-group col-md-3">
    <label for="data_saida">Leaving Date</label>
    <input type="text" id="data_saida" class="form-control"  name="data_saida" value="">
  </div>
</div>
{
  var todaydate = new Date();
  var day = todaydate.getDate();
  var month = todaydate.getMonth() + 1;
  var year = todaydate.getFullYear();
  var data_entrada = day + " / " + month + " / " + year;
  document.getElementById("data_entrada").value = data_entrada; 

  function setSaida(startDate,days){
   /* you might need a start date validation here... */
    var days = document.getElementById("data_permanecia").value;    
    var date = new Date();
    date.setDate(startDate.getDate()  + days);
    if(!isNaN(date)){
      document.getElementById("data_saida").value = date.getDate()+" / "+(date.getMonth()+1)+" / "+date.getFullYear();
    }
  }

  //listen to user's input
  const $source = document.querySelector('#data_permanecia');
  const typeHandler=function(e){
    setSaida(todaydate,e.target.value);
  }
  $source.addEventListener('input', typeHandler)
  $source.addEventListener('propertychange', typeHandler)

}

link to edit in the pen code https://codepen.io/Sderdev/pen/NWqazLM?editors=0010

1 answer

1


The problem is in the sum startDate.getDate() + days, because the value startDate.getDate() is the type number and the value days is the type string.

So he’s just concatenating values, for example:

1 + "1" = "11"


1 + 1 = 2

When this wrong sum occurs and the value of days becomes greater than 31, the setDate javascript has the intelligence to understand that we have advanced 1 month and now we are on the 1st of the following month, due to this occurs the change of days and months of your input.

To make the sum the right way, you need to transform the value days for the guy number, in that way:

date.setDate(startDate.getDate() + Number(days));

or

date.setDate(startDate.getDate() + parseInt(days));
  • Thank you very much helped worked

Browser other questions tagged

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