1
Good afternoon. I’m studying a little JS and I found something interesting that future I think about using. However I realized that the JS below that generates installments with due dates, skips the month of February.
I can’t identify where the error might be, so I can change and finally do it correctly.
Could you help me?
Code:
function correcaoDia(dia) {
if (isNaN(dia)) return false;
return dia < 10 ? "0" + dia : dia ;
}
function correcaoMes(mes) {
if (isNaN(mes)) return false;
return mes < 10 ? "0" + mes : mes ;
}
function calcularParcelas(parcelas, stringData) {
var ano = stringData.substring(6,10);
var mes = stringData.substring(3,5);
var dia = stringData.substring(0,2);
var dataInicial = new Date(ano,mes,dia);
var dataParcela = new Date();
var resultado = "";
var novoMes = 0;
var novoAno = 0;
resultado += "<ul>";
for ( var p = 0 ; p < parcelas ; p++ ) {
novoMes = ( dataInicial.getMonth() + p ) % 12;
novoMes = novoMes == 0 ? 12 : novoMes;
novoAno = dataInicial.getFullYear() + ( ( ( dataInicial.getMonth() + p ) - novoMes ) / 12 );
dataParcela.setMonth(novoMes);
dataParcela.setYear(novoAno);
resultado += "<li>";
resultado += correcaoDia(dataParcela.getDate());
resultado += "/";
resultado += correcaoMes(dataParcela.getMonth() + 1);
resultado += "/";
resultado += dataParcela.getFullYear();
resultado += "</li>";
}
resultado += "</ul>";
return resultado;
}
var parcelas = 8;
document.write(calcularParcelas( parcelas, "29/09/2016"));
He must be skipping February because he gets number 29 (next year is not leap year). If you have the date generated 29/Feb/2017, it will jump to the next day (1/Mar/2017)
– lfarroco