JavaScript Date getHours() Method

JavaScript’s Date object provides a number of methods for working with dates and times, including the getHours() method. This method returns the hour of the day (0-23) for a given date object, in the local time zone.

Here’s an example of how to use getHours() to get the current hour of the day:

let date = new Date();
let hours = date.getHours();
console.log(hours);  // Outputs the current hour of the day

You can also pass a date object as an argument to getHours() to get the hour for a specific date:

let date = new Date(2022, 0, 1, 11, 30, 0);  // January 1, 2022 at 11:30:00
let hours = date.getHours();
console.log(hours);  // Outputs 11

Note that the getHours() method returns the hour in the local time zone. If you want to get the hour in a specific time zone, you can use the getUTCHours() method instead.

Here’s an example of how to use getUTCHours() to get the hour for a date in UTC time:

let date = new Date(2022, 0, 1, 11, 30, 0);  // January 1, 2022 at 11:30:00 (local time)
let hours = date.getUTCHours();  // Get the hour in UTC time
console.log(hours);  // Outputs 10 (UTC is 1 hour ahead of local time)

You can also use the getHours() method to format the hour as a 12-hour time, like this:

let date = new Date();
let hours = date.getHours();
let ampm = (hours >= 12) ? "PM" : "AM";
hours = (hours > 12) ? hours - 12 : hours;
console.log(hours + " " + ampm);  // Outputs the current time in 12-hour format

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: