JavaScript Date getHours() Method



The JavaScript Date.getHours() method is used to retrieve the hour value of a date object according to the local time. The return value will be an integer between 0 and 23 representing the hour according to the local time zone.

If the Date object is created with no arguments, it returns the current hour in the local time zone. If the Date object is created with a specific date and time, it returns the hour component of that date in the local time zone. If the Date object is invalid, it returns NaN (Not-a-Number).

Syntax

Following is the syntax of JavaScript Date getHours() method −

getHours();

This method does not accept any parameters.

Return Value

This method returns an integer representing the hour component of the given date object, ranging from 0 to 23.

Example 1

In the following example, we are demonstrating the basic usage of JavaScript Date getHours() method −






Output

The above program returns the current hour according to the local time.

Example 2

In this example, we are retrieving the hour from the specific date and time.






Output

The above programs returns integer 15 as hour.

Example 3

According to the current local time, the program will return a greeting based on whether it is morning, afternoon, or evening.






Output

As we can see the output, respective greeting has been returned according to the local time.

Advertisements