JavaScript Date getHours() Method

Definition and Usage

getHours() The method returns the hour number of a specified date and time (from 0 to 23).

Example

Example 1

Return the hour according to local time:

var d = new Date();
var n = d.getHours();

Try It Yourself

Example 2

Return the hour of a specific date and time:

var d = new Date("July 21, 1983 01:15:00");
var n = d.getHours();

Try It Yourself

Example 3

Display time using getHours(), getMinutes(), and getSeconds():

function addZero(i) {
  if (i < 10) {
    i = "0" + i;
  }
  return i;
}
function myFunction() {
  var d = new Date();
  var x = document.getElementById("demo");
  var h = addZero(d.getHours());
  var m = addZero(d.getMinutes());
  var s = addZero(d.getSeconds());
  x.innerHTML = h + ":" + m + ":" + s;
}

Try It Yourself

Syntax

Date.getHours()

Parameters

No parameters.

Technical Details

Return Value: Numbers, from 0 to 23, represent hours.
JavaScript Version: ECMAScript 1

Browser Support

Method Chrome IE Firefox Safari Opera
getHours() Support Support Support Support Support

Related Pages

Tutorial:JavaScript Date

Tutorial:JavaScript Date Format

Tutorial:JavaScript Object Constructor