Subtract days from an input date with javascript

I need to take a data from a type Number field and add to a date from a input date. I already managed, but I need to now take the result of that date and subtract 14 days, but not getting it. I'm a beginner and I need to do this, please help me. What do I need to do to subtract 14 from the result of input date datafin?

HTML:

<input type="date" id="ini" />
<input onchange="calculater();" name="dias" type="number" id="dias" min="20" max="40" size="70" />
<input name="datafin" type="date" id="datafin" size="70" />

Javascript:

function calculater() {
    var inicial = document.getElementById("ini").value;
    var dias = parseInt(document.getElementById("dias").value);
    var partes = datainicial.split("-");
    var ano = partes[0];
    var mes = partes[1] - 1;
    var dia = partes[2];

    inicial = new Date(ano, mes, dia);
    final = new Date(inicial);
    final.setDate(final.getDate() + dias);

    var dd = ("0" + final.getDate()).slice(-2);
    var mm = ("0" + (final.getMonth() + 1)).slice(-2);
    var y = final.getFullYear();

    var dataformatada = y + '-' + mm + '-' + dd;
    document.getElementById('datafin').value = dataformatada;
}
Author: BrTkCa, 2017-01-11

2 answers

var data = new Date();

document.write('Hoje é: ' + data.toLocaleString());

data.setDate(data.getDate() - 14);

document.write('<br>14 dias atrás: ' + data.toLocaleString());

In your case:

function calculater() {
  var inicial = document.getElementById("ini").value;
  var dias = parseInt(document.getElementById("dias").value);
  var partes = inicial.split("-");
  var ano = partes[0];
  var mes = partes[1] - 1;
  var dia = partes[2];

  inicial = new Date(ano, mes, dia);
  final = new Date(inicial);
  final.setDate(final.getDate() + dias);
  final.setDate(final.getDate() - 14); // menos 14 dias do resultado

  var dd = ("0" + final.getDate()).slice(-2);
  var mm = ("0" + (final.getMonth() + 1)).slice(-2);
  var y = final.getFullYear();

  var dataformatada = y + '-' + mm + '-' + dd;
  document.getElementById('datafin').value = dataformatada;
}
<input type="date" id="ini" />
<input onchange="calculater();" name="dias" type="number" id="dias" min="20" max="40" size="70" />
<input name="datafin" type="date" id="datafin" size="70" />
 5
Author: BrTkCa, 2017-01-11 17:31:41

Tl; dr: The most correct is something like:

inicial = new Date(ano, mes, dia);
milissegundos_por_dia = 1000 * 60 * 60 * 24;
data_final = new Date(inicial.getTime() + dias * milissegundos_por_dia);

Explaining :

The Date Javascript object has some convenient methods, to access each type of value associated with the date it contains.

The method .getDate in particular retrieves the day of the month, as an integer. The problem with wanting to subtract dates using getDate() is when you get to the" borders " of a month: it's okay if it's day 15 and you want the date from 2 days ago - getDate() returns 15, you take 2, you have 13, you make a setDate, and you have the correct date of 2 days ago.

The problem is if you are on the 7th and want the date 15 days ago. Or simply want the date 30 days ago. Using getDate, you would have to make a structure of if and else so when the day of the desired month is negative, subtract one from the month, and then adjust the day appropriately. And one more if for the case of the month that returned to be from January to December, and in this case, subtract the year. It not to mention the numerous corner-cases, such as the bisexts, start and end of Daylight Saving Time, etc... it may seem trivial at first, but it is always nice to keep in mind that Microsoft itself, in the first versions of Excel miscalculated dates for the year 1900 (treating it as Leap, being that it was not-and to this day the format of dates encoded in files .XLS suffers because of this error).

Fortunately, the object Date also has the methods getTime and setTime, which instead of saying a date like Month, Day, Year, hours, minutes, and seconds in separate fields returns (and accepts) a single integer: the number of milliseconds passed since midnight on 1/1/1970.

This representation derives from the so - called" unixtime", used in servers and programs worldwide-which represents the number of seconds passed since the same date. (see that in Javascript, we have the milliseconds, not the seconds).

So given a date, all we need to calculate the subtraction (or addition) of a certain number of days is to use the .getTime, manipulate that number, and use the .setTime or create a new object Date to have how to get the "human-usable" values, of month, day, and year, of the desired date.

I.e.:

...
ano = ...;
mes = ...;
dia = ...;
...
dias = ...; 
...
inicial = new Date(ano, mes, dia);
milissegundos_por_dia = 1000 * 60 * 60 * 24;
data_final = new Date(inicial.getTime() + dias * milissegundos_por_dia);

And that's it - you have the end date without any month calculation problem, turn of the year, leap second-you reuse all the thousands of lines of code that are in the browser and the operating system to calculate the date, without having to reinvent the wheel.

 2
Author: jsbueno, 2017-11-28 02:04:25