JavaScript Date setHours() method

The setHours method in JavaScript is utilized to establish the hour for a given date according to the local time zone.

Syntax

The syntax for the setHours method is illustrated as follows:

Example

dateObj.setHours(hoursValue[, minValue[, secValue[, msValue]]])

Parameter

hoursValue - This denotes an integer ranging from 0 to 23, indicating the Hours. Should the supplied hour value exceed 23, the setHours method will adjust the day value accordingly.

minValue - This parameter is not mandatory. It indicates an integer ranging from 0 to 59, which defines the minutes. In cases where the supplied minute exceeds 59, the setHours function will adjust the hour value accordingly.

secValue - This parameter is optional. It denotes an integer within the range of 0 to 59, indicating the number of seconds. Should the supplied second value exceed 59, the setHours method will adjust the minute value accordingly.

The parameter msValue is optional. It denotes an integer ranging from 0 to 999, which indicates the milliseconds. Should the supplied millisecond value exceed 999, the setHours function will adjust the seconds value accordingly.

JavaScript Date setHours method example

In this section, we will explore the setHours method by examining a variety of examples.

Example 1

Let’s examine an example that demonstrates how to display both the current hour and the updated hour value.

Example

<script>

var hours=new Date();	

document.writeln("Current Hour : "+hours.getHours()+"<br>");

hours.setHours(8);

document.writeln("Updated Hour : "+hours.getHours());

</script>

Output:

Output

Current Hour : 13

Updated Hour : 8

Example 2

Let’s examine an instance where we modify the hour component of a specified time.

Example

<script>

var hours=new Date("August 15, 1947 20:22:10");	

hours.setHours(10);

document.writeln("Updated Hour : "+hours.getHours());

</script>

Output:

Output

Updated Hour : 10

Example 3

In this instance, we will define the minute value (exceeding 59) along with the hours.

Example

<script>

var hours=new Date("August 15, 1947 20:22:10");	

hours.setHours(10,62);

document.writeln("Updated Hour : "+hours.getHours());</script>

Output:

Output

Updated Hour : 11

Input Required

This code uses input(). Please provide values below: