Understanding the JavaScript getHours() Method: A Comprehensive Guide

In this tutorial, we will delve into one of the most useful methods in JavaScript for handling dates and times – the getHours() method. This method is part of the Date object and it’s used to get the hour for a specified date, according to local time.

Usage of getHours() Method

The syntax for using this method is quite straightforward:

var date = new Date();
var hours = date.getHours();

In this example, date is an instance of the Date object. We then call the getHours() method on this instance which returns the hour from the current date and time.

A Practical Example

To illustrate how you might use this in a real-world scenario, let’s say you want to display a different greeting message on your website depending on whether it’s morning, afternoon or evening. Here’s how you could do that with getHours():

var date = new Date();
var hours = date.getHours();

if (hours < 12) {
    document.write("Good Morning!");
} else if (hours < 18) {
    document.write("Good Afternoon!");
} else {
    document.write("Good Evening!");

This script checks what time it currently is and writes a different message to your webpage based on that time.

Note About Time Zones

The getHours() method returns values according to local time. If you need to work with UTC (Coordinated Universal Time), use the getUTCHours() method instead.


The getHours() method is a powerful tool for handling time in JavaScript. Whether you're building a dynamic greeting message, a clock, or any other feature that relies on the current hour, this method can be incredibly useful.

We hope this tutorial has helped you understand how to use the getHours() method effectively in your JavaScript projects. Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *