Javascript - Date getHours() Method

The getHours() method returns the hour ranged from 0 to 23 of the date object.

Description

The getHours() method returns the hour ranged from 0 to 23 of the date object.

Syntax

Date.getHours()

Parameters

None

Return

A Number, from 0 to 23, representing the hour

Example

Return the hour, according to local time:

Demo

//display the hour of the time right now.
var d = new Date();
var n = d.getHours();
console.log(n);//from   w w  w .j a  va 2  s . co  m

//Return the hour from a specific date and time:

//display the hour of a given date-time.
var d = new Date("July 21, 2010 01:15:00");
var n = d.getHours();
console.log(n);

Result

Using getHours(), getMinutes(), and getSeconds() to display the time:

Demo

//display the time.
function addZero(i) {
    if (i < 10) {
        i = "0" + i;
    }//from  w w w.  j av  a2s .  c  o m
    return i;
}

var d = new Date();
var h = addZero(d.getHours());
var m = addZero(d.getMinutes());
var s = addZero(d.getSeconds());
console.log( h + ":" + m + ":" + s);

Result