Introduction to JavaScript Date setUTCHours()
The setUTCHours() method of the JavaScript Date object is used to set the hour of a given date object, according to universal time. The universal time is also known as Greenwich Mean Time (GMT). This method is useful whenever you need to work with dates in a global context.
The setUTCHours() method can be used on a Date object, to set the hour of the day, to a specific value, according to universal time. This method takes a single parameter, which is the hour that is to be set. The hour is an integer value, between 0 and 23. This method does not return a value, it simply updates the Date object it was called on.
Syntax
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
dateObj.setUTCHours(hour[, min[, sec[, ms]]])
[/dm_code_snippet]
Where dateObj
is a Date object, hour
is the hour to set, min
is the minute, sec
is the second, and ms
is the millisecond.
Example
Let’s take a look at an example of how to use the setUTCHours() method. The following example sets the hour of the day, according to universal time.
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
// Create a date object var date = new Date(); // Set the hour of the date object, according to universal time date.setUTCHours(18); // Log the date to the console console.log(date);
[/dm_code_snippet]
In this example, the hour of the day, according to universal time, is set to 18. This is equivalent to 6 pm in most time zones.
Conclusion
The setUTCHours() method of the JavaScript Date object is used to set the hour of a given date object, according to universal time. This method can be used to set the hour of the day, to a specific value, according to universal time. This is a useful method, whenever you need to work with dates in a global context.