Subtract days from an input date with javascript

Asked

Viewed 9,324 times

4

I need to take a data from a type number field and add to a date of a input date. I already did, but now I need to get the result of that date and subtract 14 days, but I can’t get it. I’m a beginner and I need to do this, please help me. What I need to do to subtract 14 from the input date result 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;
}
  • I don’t understand. You want to add by the amount of input and subtract 14 days from the result?

  • There is the Input Number that goes between 20 and 40, this input sum with what the user marks in the first input date, if he marks day 01 in the date and 20 in the number the result will be marked with day 21 in the second input date, but I need to take the result of this second input date and subtract 14 days.

  • The result of this second input should already be the value - 14 days or not?

2 answers

6


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" />

  • Lucas, and how would it be to pass the input date datafin value, because I needed to subtract according to the result that appeared from the sum between the day the user marks, with the input number that he marks as well. This result is presented in another input date, now I need to take the value of this result and subtract 14.

  • This answer has a serious problem, when the final day passes the number of days of the current month. See my answer to see how to work with this.

  • Thus you say @jsbueno? I read your answer, it’s good.. if you can simulate the problem (maybe in fiddle) please.

3

tl;dr: The right thing 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 object Date Javascript has some convenient methods, to access each type of value associated with the date it contains.

The method .getDate in particular recovers the day of the month as an integer. The problem when wanting to subtract dates using the getDate() is when you arrive at the "borders" of a month: all right if it’s the 15th and you want the date 2 days ago - getDate() returns 15, you strip 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 simply want the date 30 days ago. Using getDate, you would have to make a structure of if and else for when the day of the month desired was negative, subtract one from the month, and then adjust the day accordingly. And one more if for the case of the month that returned from January to December, and in this case, subtract the year. Not to mention the numerous corner-cases, such as leap, summer time start and end, etc... may seem trivial at first, but it’s always nice to keep in mind that Microsoft itself, in the early versions of Excel, miscalculated dates for the year 1900 (treating it as leap, but it was not - and until today the date format encoded in files . XLS suffers from this error).

Fortunately, the object Date also has the methods getTime and setTime, which instead of telling a date as month, day, year, hours, minutes and seconds in separate fields, returns (and accepts) a single integer number: The number of milliseconds passed since midnight 1/1/1970.

This representation derives from the so-called "unixtime", used in servers and programs around the world - 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 do 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 obtain the values "usable by humans", of month, day and year, of the desired date.

That is to say:

...
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 problem of month calculation, 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.