I need some help with days not subtracting correctly

Hi all. I’m trying to build a calculator that works out when certain documents will expire based on the issue date of the document provided by the user. Currently in my code it is set to do this by adding 90 days to the issue date.

A second thing that also needs to be calculated is when users should reapply for the document. So if a document expires on the 3rd of May 2022 they should reapply 10 days before the expiry date.

The problem that I don’t know how to fix is that the subtraction is taking place from the current date instead of the from the expiry date.

Any advice would be greatly appreciated.

Please find the full code below and in the codepen: https://codepen.io/Nicole850206/pen/bGjRXJa

<!DOCTYPE html>

<p>Select a date: <input type="date" id="issueDate"></p>
<button onclick="addDays()">Add 90 days</button>
<button onclick="subtractDays()">Subtract 10 days</button>
<div id="expiryDate"></div>
<div id="applyDate"></div>

function addDays() {
  var date = new Date(document.getElementById("issueDate").value);
  date.setDate(date.getDate() + 90);
  document.getElementById("expiryDate").innerHTML = date;

function subtractDays() {
  var expiryDate = document.getElementById("expiryDate").value;
  var date = expiryDate ? new Date(expiryDate) : new Date();
  date.setDate(date.getDate() - 10);
  document.getElementById("applyDate").innerHTML = date;



I just forgot to change the 6 to 90 and the 3 to 10 sorry about that :smile: The way you understand it is correct. I did originally only want one button but the only way I could think of it to work was with the way I used above, which I understand now can’t work :sweat_smile:

The logic I used with a single button is:

  1. Get value of input
  2. Create a variable to hold a new Date that is either the current date (if the input’s value is undefined (nothing selected)), or a date of the same value of the input’s contents.
  3. Set the date variable to be 90 days more than it is.
  4. Set the innerHTML of the the div with id=“expiryDate” to be this date.
  5. Set the date variable to be 10 days less than it currently is.
  6. Set the innerHTML of the the div with id=“applyDate” to be this date.

That is it. There is a single function with 6 lines of code that displays the two dates with a single click of a button.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.