Javascript:getFullyear() 不是函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4929382/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:49:15  来源:igfitidea点击:

Javascript: getFullyear() is not a function

javascriptdate

提问by Prady

I am getting an error:

我收到一个错误:

Statdate.getFullyear() is not a function.

From this javascript code:

从这个javascript代码:

var start = new Date();
start = document.getElementById('Stardate').value ;

var y = start.getFullYear();

Any idea why that function isn't available?

知道为什么该功能不可用吗?

回答by limc

Try this...

尝试这个...

 var start = new Date(document.getElementById('Stardate').value);
 var y = start.getFullYear();

回答by Eric Leschinski

One way to get this error is to forget to use the 'new' keyword when instantiating your Date in javascript like this:

获得此错误的一种方法是在像这样在 javascript 中实例化 Date 时忘记使用“new”关键字:

> d = Date();
'Tue Mar 15 2016 20:05:53 GMT-0400 (EDT)'
> typeof(d);
'string'
> d.getFullYear();
TypeError: undefined is not a function

Had you used the 'new' keyword, it would have looked like this:

如果您使用了 'new' 关键字,它会是这样的:

> el@defiant $ node
> d = new Date();
Tue Mar 15 2016 20:08:58 GMT-0400 (EDT)
> typeof(d);
'object'
> d.getFullYear(0);
2016

Another way to get that error is to accidentally re-instantiate a variable in javascript between when you set it and when you use it, like this:

获得该错误的另一种方法是在您设置它和使用它之间意外地在 javascript 中重新实例化一个变量,如下所示:

el@defiant $ node
> d = new Date();
Tue Mar 15 2016 20:12:13 GMT-0400 (EDT)
> d.getFullYear();
2016
> d = 57 + 23;
80
> d.getFullYear();
TypeError: undefined is not a function

回答by JCOC611

You are overwriting the startdate object with the valueof a DOM Element with an id of Startdate.

您正在使用 ID 为 的 DOM 元素的覆盖start日期对象。valueStartdate

This should work:

这应该有效:

var start = new Date(document.getElementById('Stardate').value);

var y = start.getFullYear();