最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - TypeError: *.getMonth is not a function - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question asked Mar 14, 2014 at 20:15 Jason BoyceJason Boyce 2131 gold badge2 silver badges15 bronze badges 1
  • 1 You need to use var for all your local variables – Pointy Commented Mar 14, 2014 at 20:16
Add a ment  | 

1 Answer 1

Reset to default 11

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.

发布评论

评论列表(0)

  1. 暂无评论