JavaScript getHours(): Get the hour (0-23)

The JavaScript getHours() method is used to get the hour (0-23). For example:

HTML with JavaScript Code
<!DOCTYPE html>
   <p id="xyz"></p>

      const d = new Date();
      let hour = d.getHours();
      document.getElementById("xyz").innerHTML = hour;


In the above example, the following JavaScript statement:

const d = new Date();

creates a new "Date" object with the "new Date()" constructor. This method generates a new date and time object using the current system clock time. Now using the second or the following JavaScript statement:

let hour = d.getHours();

calls the "Date" object's getHours() method to retrieve the current hour of the day in 24-hour format (0-23). This value is saved in the variable hour.

Finally, the following JavaScript statement:

document.getElementById("xyz").innerHTML = hour;

finds the HTML element with the id attribute "xyz" and sets its innerHTML property to the value stored in the "hour" variable using the document.getElementById() method. This will display the current time on the web page.

JavaScript getHours() syntax

The syntax of the getHours() method in JavaScript is:


The x must be an object of the Date() constructor.

The getHours() method returns a number from 0 to 23, which will be an hour of the local time.

Please note: To display the date in the format dd-mm-yyyy, refer to its separate example.

Please note: To display time in the format hh:mm:ss, refer to its separate example.

Please note: To display time in the format hh:mm:ss AM/PM, refer to its separate example.

Advantages of the getHours() function in JavaScript

Disadvantages of the getHours() function in JavaScript

JavaScript Online Test

« Previous Tutorial Next Tutorial »

Liked this article? Share it!

Like/follow us on social media for updates!