开发者

Javascript: getFullyear() is not a function

开发者 https://www.devze.com 2023-02-09 07:54 出处:网络
I am getting an error: Statdate.getFullyear() is not a function. From this javascript code: var start = new Date();

I am getting an error:

Statdate.getFullyear() is not a function.

From this javascript code:

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

var y = start.getFullYear();

Any idea why that function isn't开发者_StackOverflow中文版 available?


Try this...

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


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

> 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:

> 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:

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


You are overwriting the start date object with the value of a DOM Element with an id of Startdate.

This should work:

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

var y = start.getFullYear();


All the above answers are correct. I just want to highlight one thing that I was doing wrong.

When creating a date object I was using new date().toISOString() which was the main reason that it was throwing this error.

So dont change your date object in a local string format if you are applying date.getFullYear().

0

精彩评论

暂无评论...
验证码 换一张
取 消