Solutions For The TypeError: date.getHours Is Not A Function In JavaScript

TypeError: date.getHours is not a function in JavaScript

After understanding the root cause of the TypeError: date.getHours is not a function in JavaScript, we also found a solution. So that you can understand how we solve it, please take a closer look at the cause of the error below and then see how we solve it.

Why does the TypeError: date.getHours is not a function in JavaScript occur?

To understand how the error appears, follow the example below.

Example:

const date = "12345";
console.log("Hour: ", date.getHours());

Output

Uncaught TypeError: date.getHours is not a function

The root cause of this error is: the getHours method is used on an object other than the Date object.

How to fix this error?

We found two ways to fix this:

  • Use the constructor property
  • Convert to a valid date object using the Date constructor

Use the constructor property

The constructor property

This property will return a reference to the object constructor, the object constructor that created the instance of an object.

We rely on the cause to fix this error. Check out the example below to see how we fixed it, and then we’ll explain why.

Example

// Create date object
const date = new Date();

// Check constructor is a Date constructor or not
if (date.constructor === Date) {
	console.log("Date: ", date);
	console.log("Hour: ", date.getHours());
} else {
	console.log("Error");
}

Output:

Date:  Thu Dec 08 2022 21:51:00 GMT+0700
Hour:  21

To ensure “TypeError: date.getHours is not a function” in JavaScript error doesn’t happen, we have to check if the object constructor is a Date constructor using the constructor property. If it is a Date constructor, we allow access to the getHours() method to get the time.

Convert to a valid date object using the Date constructor

The Date constructor is used to create a date object.

Syntax:

new Date(dateString)

Parameter:

  • dateString: is a date string.

There are many ways to create a date object. We only use one of those ways.

Example:

// Create a variable and assign the value as a date string
const date = "December 8 , 2022 21:00:00";

// Convert to a date object
const convertDate = new Date(date);

console.log("Date convert : ", convertDate);
console.log("Hour: ", convertDate.getHours());

Output

Date convert:  Thu Dec 08 2022 21:00:00 GMT+0700
Hour:  21

If the variable’s value is not a Date object (like String, Number), then we convert it to a date object using the Date constructor. Then use the getHours method to get the hour.

Summary

To avoid the TypeError: date.getHours is not a function in JavaScript, you must make sure that you use the getHours method on a date object. If you want to read more bug fixes like this, follow us; we constantly update articles like this daily.

Maybe you are interested:

Leave a Reply

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