javascript 类型错误:*.getMonth 不是函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22414903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: *.getMonth is not a function
提问by Jason Boyce
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:
我正在尝试构建一个 javascript 函数,该函数将自动填充日历的 14 天,并使用日期选择器选择的最后一个日期之前的日期。到目前为止,我的代码是:
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;"
然而,开发人员的控制台一直告诉我 date1.getMonth 不是一个函数。我很困惑,因为我一直在查看的所有教程和示例都基于以下内容:“var today = new Date(); var month = today.getMonth() + 1;”
Is this an implementation problem?
这是一个实施问题吗?
回答by Pointy
The setDate()
function mutates its context date. It does not return a new Date instance.
该setDate()
函数会改变其上下文日期。它不会返回新的 Date 实例。
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:
然后,如果你有一个日期,你可以像这样在它之后的 14 天创建一个日期:
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.
然后,您可以使用.getMonth()
和.getDate()
访问器来执行您想要的任何格式。请记住,在 JavaScript 中,月份是从零开始编号的。
editfor dates beforea date just pass a negative number.
编辑日期之前的日期只需传递一个负数。