add days to a specific date with java script


I have a date in format dia-mes-año 15-02-1981, I would like to be able to add days to that date.

The examples that I have been seeing, I do not know why but I add months not days.

I'm trying the next code.

Ffin="15-02-1981"; //Este seria el formato de la fecha que recibo de la variable

let Ffin="15-02-1981";
fecha = new Date(Ffin);
entrega = new Date(Ffin);
dia = fecha.getDate(Ffin);
mes = fecha.getMonth()+1;// +1 porque los meses empiezan en 0
anio = fecha.getFullYear();
entrega.setDate(entrega.getDate(Ffin) +1 );

alert(entrega.getDate(Ffin) + "/" +
(entrega.getMonth(Ffin)+1) + "/" +

I always add to the month not to the day

asked by Lorenzo Martín 15.11.2018 в 17:49

2 answers


Separate the problem into 2 functions, 1 call parseDate through which you pass your date with the format you indicate and it returns an object instance of type Date valid, and the second sumDays is responsible for add n days to a date that you pass as the first parameter. Since your format is day-month-year and to parse it correctly to Date it must be at least one of the variants month / day / year, I convert the entry so it has that format and then pause the date.

var parseDate = function(date){
  var parts = date.split('-');
  var temp = parts[0];
  parts[0] = parts[1];
  parts[1] = temp;
  return new Date(Date.parse(parts.join('/')));  

var sumDays = function(date, days){
  var fdate = parseDate(date);
  return fdate;

And to prove it really works:

sumDays("15-02-1981", 3);
//Te muestra en la consola
//Date 1981-02-18T05:00:00.000Z


sumDays("15-02-1981", 20);
//Date 1981-03-07T05:00:00.000Z
answered by 15.11.2018 / 18:40

To add days you can use this method:

dias = 3;
fecha = new Date(); // ó new Date(valor);
fecha.setDate(fecha.getDate() + dias);

Edit: If you need to enter the date in a specific format, you can use the library moment.js

dias = 3;
fecha = '15-02-1981'; // string
fechaMoment = moment(fecha,'DD-MM-YYYY').add(3, 'day');

Then you can transform the moment object to a Date object:

fechaMoment.toDate(); // Wed Feb 18 1981 ...

Or print it with format:

fechaMoment.format('DD-MM-YYYY'); // 18-02-1981

You can read more about how to manipulate dates with momentum in your documentation .

answered by 15.11.2018 в 18:38