Javascript: getFullyear() is not a function
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 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();