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

featured Image

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

Related Posts

featured Image

Get the 10 characters from a string using JavaScript.

Here, in this article we will learn how to get the first 10 character from any string using JavaScript. Here we will be using JavaScript’s String method substring. What is…

Read more
featured Image

Convert date to long date format using JavaScript

In this article we will look into how to convert a date to a long date format using JavaScript. To convert it to a long format we will be using…

Read more
featured Image

Prevent body from scrolling when a modal is opened

Here, in this article, we will learn how to prevent the body from scrolling when a modal or a pop-up is opened using JavaScript. The scroll event is not cancelable….

Read more

Leave a Reply

Your email address will not be published. Required fields are marked *