JavaScript function to add days, is adding up a month ahead

4

I'm with this JavaScript function that is adding the days to a date, the days it adds up right, only instead of adding it to 10/24/2017 + 2 days = 10/26/2017 , he plays a month ahead, so stay that way 24/10/2017 + 2 days = 26/11/2017. Here's how I'm doing:

 now = new Date;
 var dia_atual = now.getDate();
 var dia_escolha = document.getElementById("<%= txtDiaVencimento.ClientID %>").value;
 if ($("#<%=txtTipodePlano.ClientID %>").val() == "MENSAL") {
     if (parseInt(dia_escolha) > parseInt(dia_atual)) {
         var total_dias = dia_escolha - dia_atual;
         var data_tolerancia;
         var tol = (document.getElementById("<%= txtDiaVencimento.ClientID %>").value);
         var data = toDate(document.getElementById("<%= txtDataInicio.ClientID %>").value);

         function toDate(data) {
             let partes = data.split('/');
             return new Date(partes[2], partes[1], partes[0]);
         }
         data.setDate(data.getDate() + total_dias);
         document.getElementById("<%= txtVencimentoC.ClientID %>").value = data.format("dd/MM/yyyy HH:mm:ss");
         data.setDate(data.getDate() + parseInt(total_dias));
         document.getElementById("<%= txtDataTolerancia.ClientID %>").value = data.format("dd/MM/yyyy HH:mm:ss");
     }
    
asked by anonymous 24.10.2017 / 18:27

1 answer

4

The date of the JavaScript Date object has the period between 0 (January) and 11 (December) and not between 1 and 12.

So, in your calculation, you can subtract the month from the user input by -1.

return new Date(partes[2], (partes[1] - 1), partes[0]);

Additional links:

MDN-JavaScript Date

Problem with time display

    
24.10.2017 / 18:34