0

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.

2
  • Why 30 and not 31 or 28 or sometimes 29? ...just making sure 30 is for no reason 30... Commented May 16, 2020 at 1:39
  • @RokoC.Buljan Because this calculates when an invoice was sent and when it is due which is always 30 days Commented May 16, 2020 at 1:41

2 Answers 2

1

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');
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.