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.
The getHours
method does not take any parameters.
The getHours
method returns an integer between and 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 , 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.
The code below shows how the getHours
method works in Javascript:
// initializing date objectsvar 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 hoursconsole.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());
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., and , respectively.
On the other hand, object c
has an invalid value for its number of days (). 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