TypeError: * .getMonth is not a function

I am trying to create a javascript function that will automatically populate 14 days of a calendar with dates preceding the last date that datepicker has selected. 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 console continues to tell me that date1.getMonth is not a function. I got confused because all the tutorials and examples I looked at are based on something like: "var today = new Date (); var month = today.getMonth () + 1;"

Is this an implementation issue?

+4
source share
1 answer

The function setDate()changes the date of its context. It does not return a new instance of Date.

, :

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

, , 14 :

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

.getMonth() .getDate() . , JavaScript.

, .

+11

Source: https://habr.com/ru/post/1531847/


All Articles