Matthew
Matthew

Reputation: 1655

Javascript - Adding 30 Days to Input Date

I can't seem to find anything recent, and it's possible I might be behind the times and am just searching the wrong terms and such so I am hoping someone here can be helpful or might have some suggestions.

I have two date fields, one an invoice date and one a due date. What I'd like to happen is that I choose or change a date in the invoice date and the due date is automatically updated to reflect a date 30 days after the invoice date.

<input id="dateInvoice" type="date"/>
<input id="dueDate" type="date"/>

Upvotes: 1

Views: 4090

Answers (3)

gurvinder372
gurvinder372

Reputation: 68373

You can follow this approach

  • parse the input date value to date using split and date constructor
  • Add days using setDate
  • Set the new date value to output date.

Demo

document.querySelector("#addDays").addEventListener("click", function() {
  var invoiceDate = document.querySelector("#invoiceDate").value;
  var days = Number(document.querySelector("#days").value);
  var dueDateElement = document.querySelector("#dueDate");

  if (!isNaN(days) && invoiceDate.length) {
    invoiceDate = invoiceDate.split("-");
    invoiceDate = new Date(invoiceDate[0], invoiceDate[1] - 1, invoiceDate[2]);
    invoiceDate.setDate(invoiceDate.getDate() + days);
    dueDateElement.valueAsDate = null;
    dueDateElement.valueAsDate = invoiceDate;
    //console.log(invoiceDate, dueDateElement.value);
  }
});
Invoice Date <input type="date" id="invoiceDate"> <br><br> Add Days <input type="text" id="days"> <br><br>

<button id="addDays">Add Days</button> <br><br> Due Date <input type="date" id="dueDate">

Upvotes: 3

Anirudha Gupta
Anirudha Gupta

Reputation: 9279

You can create the date in Javascript like this

var date = new Date(2017,11,27,11,14,00,00)

you can add 30 days to this date to get the date (after 30 days)

after30days = date.setDate(cur.getDate() + 30);

Upvotes: 1

Vikas Suryawanshi
Vikas Suryawanshi

Reputation: 522

you can split the javascript date into month day and year and add simple month to it as

var invoiceDate = new Date("01/31/2017");
var dueDate= invoiceDate.addMonths(1);

Upvotes: 0

Related Questions