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

Asked

Viewed 247 times

4

I’m with this Javascript function that’s adding up the days on a date, the days it sums up right, only instead of it adding up 24/10/2017 + 2 days = 26/10/2017, He plays a month forward, then he gets like this 24/10/2017 + 2 days = 26/11/2017. Go on like 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");
     }

1 answer

4


Javascript Date object month 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 in -1.

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

Additional links:

MDN - Javascript Date

Problem with time display

  • I did not know that, that good, but now it worked and it was clear, thank you very much.

Browser other questions tagged

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