JavaScript Date getHours()

Posted by

Method

JavaScript Date getHours() Method

The JavaScript getHours() method is used to get the hour value of the Date object. The hour value is an integer between 0 and 23. This method is a part of the Date object, and can be used to get or set the hour value of any Date object.

Syntax

The syntax for the getHours() method is as follows:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

dateObj.getHours() 

[/dm_code_snippet]

Where dateObj is a Date object.

Example

The following example demonstrates the use of the getHours() method:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

var d = new Date(); 
var h = d.getHours(); 
document.write("The hour is " + h);

[/dm_code_snippet]

This example will output the following:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

The hour is 18

[/dm_code_snippet]

The hour value is 18 because the example was run at 6PM.

Notes

The getHours() method returns the hour value from 0 to 23. This is different from the getUTCHours() method, which returns the hour value from 0 to 11.

The getHours() method can also be used to set the hour value of the Date object. The syntax for setting the hour value is as follows:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

dateObj.setHours(hourValue)

[/dm_code_snippet]

Where dateObj is a Date object, and hourValue is a number between 0 and 23.