Borislav Hadzhiev
Wed Oct 20 2021·2 min read
Photo by Mathilda Khoo
The "getMonth is not a function" error occurs for multiple reasons:
new
operator when instantiating a Date
object.getMonth()
method on an object that's not a valid Date.getMonth
method.new Date().getMonth()()
.Here are some examples of how the error occurs:
// ⛔️ did not use `new` operator const m1 = Date('Sept 24, 22 13:20:18').getMonth(); // ⛔️ did not spell `getMonth` correctly const m2 = new Date('Sept 24, 22 13:20:18').getmonth(); // ⛔️ added second set of parenthesis const m3 = new Date('Sept 24, 22 13:20:18').getMonth()(); // ⛔️ not calling getMonth on a valid date object const m4 = {}.getMonth();
In the first example, we did not use the new
operator to create the Date
object, which is what caused the error.
In the second example, we didn't capitalize the getMonth() 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 getMonth
method on an object that isn't a valid
Date
object.
To solve the "getMonth is not a function" error, make sure to only call the
getMonth()
method on a valid Date
object, e.g.
const m1 = new Date('Sept 24, 22 13:20:18').getMonth();
. The getMonth
method
returns a zero based value representing the month of the date.
const m1 = new Date('Sept 24, 22 13:20:18').getMonth(); console.log(m1); // 👉️ 8
The getMonth
method can only be called on a valid date object and returns an
integer between 0 and 11, representing the month in the given date. For example,
0
is January and 11
is December.
If you need to get the current month, you don't need to pass anything to the Date() constructor.
const current = new Date().getMonth(); console.log(current);
Note that if you pass an invalid date to the Date()
constructor, the
getMonth
method will return NaN
(not a number).
const m1 = new Date('invalid').getMonth(); console.log(m1); // 👉️ NaN
You can console.log
the value you are calling the getMonth
method on and see
if it's a valid Date
object.
getMonth
on a valid Date
object.