Subtract days from an input date with javascript

3

I need to get a data from a type number field and add it to a date of input date. I already have, but I must now take the result of that date and subtract 14 days, but I can not do 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;
}
    
asked by anonymous 11.01.2017 / 17:29

2 answers

3

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" />
    
11.01.2017 / 17:36
1

tl; dr : The most correct is something like this:

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 object has some convenient methods to access each type of value associated with the date it contains.

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

The problem is if you are on the 7th and want the date 15 days ago. Or just want the date 30 days ago. Using getDate, you would have to make a structure of if and else for when the desired day of the month was negative, subtract one from the month, and then set the day accordingly. And another if for the case of the month that came back from January to December, in which case, subtract the year. Not to mention the numerous corner-cases, such as leap times, start and end of daylight saving time, etc. ... may seem trivial at first, but it's always nice to keep in mind that Microsoft itself, in early versions of Excel, missed the calculation of dates for the year 1900 (treating it as a leap, since it was not - and to this day the date format encoded in .XLS files suffers because of this error).

Fortunately, the Date object also has methods getTime and setTime , which instead of saying a date as month, day, year, hours, minutes, and seconds in separate fields, returns (and accepts) a single integer: The number of milliseconds since midnight 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 in Javascript, we have the milliseconds, not the seconds).

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

That is:

...
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 ready - you have the final date with no problem of month calculation, year-round, leap second - you reuse all the thousands of lines of code that are in the browser and operating system to calculate the date without needing reinvent the wheel.

    
28.11.2017 / 02:56