Home >>JavaScript Date Object Methods >JavaScript setHours() Method

JavaScript setHours() Method

JavaScript setHours() Method

JavaScript setHours() method is used to set the hour of a date object. It can also be used to set the minutes, seconds and the milliseconds. It returns a new date with updated hour value.

Syntax:
Date.setHours(hour, min, sec, millisec)

Parameter Values

Parameter Description
hour This is a required parameter. It defines an integer representing the hour.
min This is an optional parameter. It defines an integer representing the minutes.
sec This is an optional parameter. It defines an integer representing the seconds
millisec This is an optional parameter. It defines an integer representing the milliseconds.

Browser Support

Method Chrome Edge Firefox Safari Opera
setHours() Yes Yes Yes Yes Yes
Here is an example of JavaScript setHours() method:
<html>
<body>
<p>Click the button to see the Output.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() 
{
  var d = new Date();
  d.setHours(14);
  document.getElementById("demo").innerHTML = d;
}
</script>
</body>
</html>
Output:

Click the button to see the Output.

Example 2:
<html>
<body>
<p>Click the button to see the Output.</p>
<button onclick="myFunction1()">Try it</button>
<p id="demo1"></p>
<script>
function myFunction1() 
{
  var d = new Date();
  d.setHours(12, 43, 4);
  document.getElementById("demo1").innerHTML = d;
}
</script>
</body>
</html>
Output:

Click the button to see the Output.


No Sidebar ads