Search code examples
javascriptjquerydatepicker

TypeError: *.getMonth is not a function


I'm trying to build a javascript function that will auto-fill 14 days of a calendar with dates leading up to the last date, which is picked by a datepicker. So far my code is:

function filldates() {

datepicked = document.getElementById("period-ending").value;
s = datepicked.split('/');
enddate = new Date(s[2], s[0], s[1]);
date1 = enddate.setDate(enddate.getDate()-14);
day1 = date1.getMonth() + 1;
month1 = date1.getDate();
var firstday = day1 + '/' + month1;
document.getElementById("date-1").value = firstday;
}

However the developer's console keeps telling me that date1.getMonth is not a function. I'm confused because all of the tutorials and examples I've been looking at are based around something like: "var today = new Date(); var month = today.getMonth() + 1;"

Is this an implementation problem?


Solution

  • The setDate() function mutates its context date. It does not return a new Date instance.

    If you want to create a new date instance that's some number of days ahead of another one:

    function daysAfter(d, days) {
      var nd = new Date(d.getTime());
      nd.setDate(d.getDate() + days);
      return nd;
    }
    

    Then if you've got a date, you can create a date 14 days after it like this:

    var someDate = ... whatever ... ;
    var fourteenDaysAfter = daysAfter(someDate, 14);
    

    You can then use the .getMonth() and .getDate() accessors to do whatever formatting you want. Keep in mind that months are numbered from zero in JavaScript.

    edit for dates before a date just pass a negative number.