The getUTCHours()
method in JavaScript is a part of the Date
object and is used to get the hours (0-23) for a given date object, in the UTC time zone. This can be useful for getting the hours in a specific time zone, or for working with dates and times in a consistent time zone.
Here’s an example of how to use getUTCHours()
to get the current hours in UTC time:
let date = new Date();
let hours = date.getUTCHours();
console.log(hours); // Outputs the current hours in UTC time
You can also pass a date object as an argument to getUTCHours()
to get the hours for a specific 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();
console.log(hours); // Outputs 11
Note that the getUTCHours()
method returns the hours as a number between 0 and 23, with 0 representing midnight and 23 representing 11 PM.
In addition to getting the hours, you can also use the setUTCHours()
method to set the hours for a date object in UTC time. Here’s an example of how to use it:
let date = new Date();
date.setUTCHours(12); // Set the hours to 12
console.log(date); // Outputs the current date and time with the hours set to 12 in UTC time
Leave a Reply