date.getDate() is not a function error in JavaScript – Fixed

In this short post, we will see why we get and how to solve the “date.getDate() is not a function” Error in Javascript.

The error “date.getDate() is not a function” occurs when we call the method (getDate()) on a value which is not a valid date object. To solve this error, we have to make sure that the method is called only on valid date objects.

Let’s see a demonstration of how this error might occur.

const date = '2022-09-04'

console.log(date.getDate())

This will give us an error like this.

TypeError: date.getDate is not a function

This is because even though the date looks like it’s in the correct date format, it actually just a string.

So we cannot use the getDate() method on a date string.

So how to solve the “date.getDate() is not a function” error?

To use the getDate() method on the above date string, we have to first convert it into a valid date object.

To convert we have to use the new Date() constructor in javascript. This will return us a valid date.

Example:

const date = '2022-09-04'
const validDate = new Date(date)

console.log(validDate.getDate()) // 4

Here, we have converted the date (‘2022-09-04’) into a valid Date object using new Date() constructor, and then called the getDate() method on it.


Related Topics:

JavaScript – Get Month Name from Date

Get Tomorrow’s Date using JavaScript – Quick Way

Get Current Date in Different Date Formats in JavaScript

Get Yesterday date in JavaScript

Scroll to Top