JavaScript

TypeError: Date.getTime is not a Function in JavaScript

The date.getTime() method is utilized to give the milliseconds that have passed since the first of January 1970. The date and time information is stored in the newly created Date object. When this date object’s getTime() method is invoked, it gives the number that represents milliseconds since January 1970. (Unix Epoch).

This blog will illustrate:

How Does the “TypeError: Date.getTime is not a Function in JavaScript” Error Occur?

JavaScript throws an error “TypeError: date.getTime is not a function” when the getTime() method calls on the non-Date object values.

Let’s practically check out the stated reason.

Example

In the following example, create a variable “date” that stores UNIX epoch timestamps using the “Date.now()” method. Here, the Date.now() method gives the UNIX timestamp in an integer number:

var date= Date.now();

Print the UNIX epoch timestamp on the console:

console.log(date);

Now, call the “getTime()” method on the integer type UNIX timestamp and store it in the variable named “time”:

var time = date.getTime();

Print the time on the console using the “console.log()” method:

console.log(time);

As you can see in the output, the “date.getTime is not a function” error occurred because the getTime() method only calls on the values of the Date object:

How to Fix the “TypeError: Date.getTime is not a Function in JavaScript” Error?

To fix the error, first, convert the value to a Date object before invoking the getTime() method or ensure that the getTime() method is only called on valid/properly formatted date objects.

Example

Create a new Date object and pass the UNIX timestamp by getting Date.now() method as an argument. It will convert the integer type UNIX date into a Date object:

var gt = new Date(date);

Invoke the “getTime()” method and store the output time in variable “time”:

var time = gt.getTime();

Print the resultant time on the console:

console.log("Current Time: " + time);

It can be observed that the stated error has been resolved successfully:

We have compiled the essential details relevant to the specified error and its solution.

Conclusion

When the getTime() method is invoked on the non-Date object values, an error occurs “TypeError: date.getTime is not a function”. To fix the error, first, convert the date value into a Date Object utilizing the Date() constructor and then utilize it. In this blog, we illustrated how the TypeError: Date.getTime is not a function in JavaScript that occurs and its relevant solution.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.