Reputation: 152
I'm trying to set two dates into two different HTML date inputs. One for today and one for 30 days in the future. Here is my code:
function SetDate(date, dest){
var dd = String(date.getDate()).padStart(2, '0');
var mm = String(date.getMonth() + 1).padStart(2, '0');
var yyyy = date.getFullYear();
document.getElementById(dest).value = yyyy + '-' + mm + '-' + dd;
}
const date = new Date();
SetDate(date, 'sent');
SetDate(date.setDate(date.getDate() + 30), 'due');
This works for today's date and set's the correct date into the first HTML input, however, when it tries to set the second date 30 days in advance I get this error
Uncaught TypeError: date.getDate is not a function ... myscript.js:2
I just can't seem to figure out what the problem is.
Upvotes: 0
Views: 79
Reputation: 206007
By doing date.setDate(date.getDate() + 30)
you'll get the number of MS.
You need to add days to a new Date()
and return a new Date()
const dateToISO8601 = (date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2,'0')}-${String(date.getDate()).padStart(2,'0')}`;
const dateAddDays = (date, days) => new Date(new Date().setDate(date.getDate() + days));
const EL = (sel, par) => (par || document).querySelector(sel);
const dateNow = new Date();
EL('#sent').value = dateToISO8601(dateNow);
EL('#due').value = dateToISO8601(dateAddDays(dateNow, 30));
<input id="sent">
<input id="due">
Upvotes: 0
Reputation: 3089
Your function SetDate
expects a Date
object as the first parameter. When you call
SetDate(date.setDate(date.getDate() + 30), 'due');
you are passing a number, not a date, because date.setDate(date.getDate() + 30)
will return a number. You can fix this by doing something like:
let date = new Date();
SetDate(date, 'sent');
date.setDate(date.getDate() + 30);
SetDate(date, 'due');
Upvotes: 1