Borislav Hadzhiev
Last updated: Jul 25, 2022
Check out my new book
The "getFullYear is not a function" error occurs for multiple reasons:
new
operator when instantiating a Date
object.getFullYear()
method on an object that's not a valid Date.getFullYear
method.new Date().getFullYear()()
.Here are some examples of how the error occurs:
// ⛔️ did not use `new` operator const d1 = Date('Sept 24, 22 13:20:18').getFullYear(); // ⛔️ did not spell `getFullYear` correctly const d2 = new Date('Sept 24, 22 13:20:18').getFullyear(); // ⛔️ added second set of parenthesis const d3 = new Date('Sept 24, 22 13:20:18').getFullYear()(); // ⛔️ not calling getFullYear on a valid date object const d4 = {}.getFullYear();
In the first example, we didn't use the new
operator to create the Date
object, which is what caused the error.
In the second example, we didn't capitalize the getFullYear() method correctly.
In the third example, we added an additional set of parenthesis, which ended up trying to call the method on an integer.
The fourth example calls the getFullYear
method on an object that isn't a
valid Date
object.
To solve the "getFullYear is not a function" error, make sure to only call the
getFullYear()
method on a valid Date
object, e.g.
const d1 = new Date('Sept 24, 22 13:20:18').getFullYear();
. The getFullYear
method returns the year of the date object it was called on.
const d1 = new Date('Sept 24, 22 13:20:18').getFullYear(); console.log(d1); // 👉️ 2022
The getFullYear
method can only be called on a valid Date
object and returns
a four-digit number representing the year.
If you need to get the current year, you don't need to pass anything to the Date() constructor.
const current = new Date().getFullYear(); console.log(current);
If you pass an invalid date to the Date()
constructor, the getFullYear
method will return NaN
(not a number).
const d1 = new Date('invalid').getFullYear(); console.log(d1); // 👉️ NaN
You can console.log
the value you are calling the getFullYear
method on and
see if it's a valid Date
object.
getFullYear
method on valid Date
objects.