Javascript Reference - JavaScript getHours() Method








getHours()
Returns the date's hours as a number between 0 and 23.

Browser Support

getHours() Yes Yes Yes Yes Yes

Syntax

dateObject.getHours();

Parameters

None

Return Value

return a number from 0 to 23 representing the hour.





Example


var myDate = new Date();
console.log(myDate.getHours());

The code above generates the following result.

Example 2

The following code returns the hour from a specific date and time:


<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {<!--  w  w  w  . jav  a2  s.com-->
    var d = new Date("July 12, 1976 01:23:00");
    var n = d.getHours();
    document.getElementById("demo").innerHTML = n;
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 3

The following code displays the hours in two digits.


<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function addZero(i) {<!--from www  . j  ava  2 s.c o  m-->
    if (i < 10) {
        i = "0" + i;
    }
    return i;
}

function myFunction() {
    var d = new Date();
    var x = document.getElementById("demo");
    var h = addZero(d.getHours());
    x.innerHTML = h;
}
</script>

</body>
</html>

The code above is rendered as follows: