JavaScript Date getHours() Method

JavaScript Date getHours() method returns the hours for this date according to local time.

Syntax

Date.getHours()

Parameters

It does not take any parameters.

Return value

It returns the Hours for the given Date object. Hours is an integer value ranging from 0 to 23.

Example 1: Usage of Date getHours()

let newDt = new Date('September 18, 1996 04:35:32');
 
let date = newDt.getHours();

console.log(date);

Output

4

Example 2: Passing no hours

If hours are not given, it returns zero (0). It is an exceptional case.

let date = new Date('September 10, 1993');
 
let hours = date.getHours();

console.log(hours);

Output

0

Example 3: Returning NaN

The getHours() method of the Date object returns the hour (from 0 to 23) of the specified date and time. If it returns NaN, that typically means there’s an issue with how the Date object was constructed or with the value of the Date object.

let date = new Date('September 32, 1993 16:35:32');

let hours = date.getHours();

console.log(hours);

Output

NaN

Example 4: Passing no arguments

let date = new Date();

let hours = date.getHours();

console.log(hours);

Output

18

Browser Compatibility

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

That’s it!

Related posts

JavaScript Date getDate()

JavaScript Date setDate()

JavaScript Date getDay()

JavaScript Date getFullYear()