0

There is a problem when I set the maxdate based on current date.

Here is the code:

var minDate = new Date();
var maxDate = new Date();

function myFunction() {
  maxDate.setDate(new Date().getDate() + 60);
  document.getElementById("demo").innerHTML = maxDate;
}
<p>Click the button to display the maxDate</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

Everytime I click on a button date is increasing by 60 days.

I want to validate it with the date entered in date input, my validation is as below.

Date entered in input should be between current date and 60 days after current date.

Output:
On click of button.
1st Click : Tue Aug 28 2018 11:36:52 GMT+0530 (India Standard Time)
2nd Click : Sun Oct 28 2018 11:36:52 GMT+0530 (India Standard Time)
3rd Click : Fri Dec 28 2018 11:36:52 GMT+0530 (India Standard Time)

Please help.

fen1x
  • 5,616
  • 6
  • 28
  • 39
Chirag Nimavat
  • 165
  • 2
  • 4
  • What do you mean increasing by 60 days? On each click it increases by 60 days? Or its showing +60 days from current date on each click – Aseem Upadhyay Jun 29 '18 at 06:16
  • *setDate* changes the Date object in place, so *maxDate* increases each time you run the function. No surprises there. – RobG Jun 29 '18 at 10:45

1 Answers1

2

new Date().getDate() returns the day of the month for current date according to local time - my current local date is 29 June 2018, so it returns 29.

That means that new Date().getDate() + 60 returns 89.

maxDate.setDate(89) sets the day of the maxDate object relative to the beginning of the currently set month.

maxDate is in global scope - that means currently set month in maxDate is changed after each click.

Try making maxDate local to your function:

function myFunction() {
  let maxDate = new Date();
  maxDate.setDate(new Date().getDate() + 60);
  document.getElementById("demo").innerHTML = maxDate;
}
<p>Click the button to display the maxDate</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
fen1x
  • 5,616
  • 6
  • 28
  • 39
  • You should also add what `newDate.getDate()` returns currently. people will get confused by the number 89 or how did the number 89 arrive – Aseem Upadhyay Jun 29 '18 at 06:29
  • I think the OP already understands the first 3 paragraphs. The 4th may be a revelation. It might be better if *myFunction* accepts a Date for *maxDate*, but defaults to the current date, e.g. `function myFunction(maxDate = new Date()){...}`. ;-) – RobG Jun 29 '18 at 10:50