Add a date in JavaScript within a for

1

What happens is that I have a code and I want to implement it within a for or something in JavaScript so that for example I have the date 09/15/2018, I add it to 15 days to be something like 09/30/2018, 10/15/2018, 10/30/2018 and so on ...

FechaPrimerPagoInput = $('#input-date').val();
fechaPrimerPago = new Date(FechaPrimerPagoInput);
periocidad = 1000 * 60 * 60 * 24 * 15;
suma = fechaPrimerPago.getTime() + periocidad;
pagoFecha = new Date(suma);

Please help, it's something simple but not used with the Date, in the variable periodicity is at the end on the 15th, which would be every count, but can change from 15 to 30.

    
asked by Jhojan Guerrero 22.08.2018 в 18:49
source

3 answers

0

Here is a possible solution to your question.

// Out
var resultado = null;

// Objeto Date
resultado = new Date();
// Suma
resultado = resultado.setDate( resultado.getDate() + 15 );      // 15, 30 ...
// Out Resultado 1
console.log(resultado);
// Out Resultado 2
console.log(new Date(resultado));

// Operar con fechas y string
var dateString = "01/01/2018";
var dateParts = dateString.split("/");
var date = new Date(dateParts[2], dateParts[1] - 1, dateParts[0],1);
// Suma
resultado = new Date(date);
resultado = resultado.setDate( date.getDate() + 15 );           // 15, 30 ...
// Out Resultado 1
console.log(resultado);
// Out Resultado 2
console.log(new Date(resultado));
    
answered by 22.08.2018 в 19:05
0

Taken from this answer:

Date.prototype.agregarDias = function(dias) {
    var fecha = new Date(this.valueOf());
    fecha.setDate(fecha.getDate() + dias);
    return fecha;
}

var hoy = new Date();

console.log(hoy.agregarDias(15));


console.log(hoy.agregarDias(30));

Inside a for:

Date.prototype.agregarDias = function(dias) {
    var fecha = new Date(this.valueOf());
    fecha.setDate(fecha.getDate() + dias);
    return fecha;
}

var hoy = new Date();


for(let i = 15; i<=365; i = i+15){

console.log(hoy.agregarDias(i))

}

That gives us the dates every 15,30,45 days for 365 days. You could also start from the previous date, but it's almost the same.

    
answered by 22.08.2018 в 19:09
0

Try this to see if it's what you need:

$(document).on('change', '#input-date', function() {
  fecha = $(this).val().match(/(\d+)/g);
  ciclos = 3;
  cantidadFechas = 15;
  fechaPrimerPago = new Date(fecha[0], fecha[1]-1, fecha[2]);
  for (i = 0; i < ciclos; i++) { 
    fechaPrimerPago.setDate(fechaPrimerPago.getDate() + cantidadFechas);
    alert(fechaPrimerPago);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input-date" type="date">
    
answered by 22.08.2018 в 22:05