What is getHours in Javascript?

The getHours method in Javascript returns the hour from a specified Date object according to the system’s local time.

The process is illustrated below:

To use the getHours method, you will need to use the following command:

dateObj.getHours()

In the code shown above, dateObj represents any Date object in Javascript.

Parameters

The getHours method does not take any parameters.

Return value

The getHours method returns an integer between 00 and 2323 that represents the hour for a given Date object according to the system’s local time.

If the Date object is invalid, e.g., the number of days in the Date object exceeds 3131, then the getHours method returns NaN (Not-A-Number). Similarly, if the Date object is empty, then the getHours method returns the present hour according to local time.

Code

The code below shows how the getHours method works in Javascript:

// initializing date objects
var a = new Date("June 29, 2021 10:15:34");
var b = new Date("June 29, 2021 01:50:06");
var c = new Date("June 45, 2021 11:20:35");
var d = new Date();
// extracting hours
console.log("The hour for a is: ", a.getHours());
console.log("The hour for b is: ", b.getHours());
console.log("The hour for c is: ", c.getHours());
console.log("The hour for d is: ", d.getHours());

Explanation

First, the code initializes multiple Date objects. The getHours method proceeds to extract the hour value of each object and outputs the result.

Since objects a and b are valid Date objects, the getHours method successfully returns the hour value for each, i.e., 1010 and 11, respectively.

On the other hand, object c has an invalid value for its number of days (4545). As a result, the getHours method returns NaN (Not-A-Number). Similarly, object d is initialized as an empty Date object, so the getHours method returns the present hour according to the system’s local time.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved