0

Below is my JavaScript Code to try and create a Maximum date where the user can't book past so many months into the future:

var x= 12;
var arriveDate = "28/11/2018"
var currentDate = new Date();
var a_date = new Date(arriveDate);
var max_month = currentDate.setMonth(currentDate.getMonth()+ x);

if (arriveDate === ""){
        $("#arrive_date_error").html("Please don't leave this field blank");
    }
    else if (a_date < currentDate){
        console.log("Please don't select a date in the past")
    }
    else if (a_date > max_month){
        console.log("date in future")
    }

The last else if never seems to work no matter what month/day/year I try. I decided to use console.log(max_month) to see what month it was creating and it returned: 1574953488195 Rather than the correct format: Thu Nov 28 2019 15:04:48 GMT+0000

What am I doing wrong and why is it changing the format when I try to change the month of the date object?

Cameron Ward
  • 25
  • 1
  • 13
  • "28/11/2018" is not a format supported by ECMA-262 (or any implementation I know of). It might result in an invalid date, or a date for 11 April 2020. Or something else. – RobG Nov 29 '18 at 03:10

1 Answers1

1

setMonth mutates the currentDate, it does not return a new date. You probably want to clone the date and set the months of that cloned one:

 var max_month = new Date(+currentDate);
 max_month.setMonth(max_month.getMonth() + x);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • 1
    _"...it does neither return a new date **nor something else**"_ - [`.setMonth()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMonth) returns the number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. – Andreas Nov 28 '18 at 15:16
  • This worked for me, thanks. Would this be the best solution in order to get x amount of months in the future? – Cameron Ward Nov 28 '18 at 15:20
  • 1
    @cameronWard yes, at least it works in all cases. In the longterm you migut want to have a look at momentJS as it is easier to use. – Jonas Wilms Nov 28 '18 at 15:22
  • It's very likely that `new Date(currentDate)` returns an invalid date. The subsequent calls to *set/getMonth* don't alter that, it remains an invalid date. – RobG Nov 29 '18 at 03:14