Javascript Reference - JavaScript setHours() Method








setHours(hours)
Sets the date's hours. Setting the hours to a number greater than 23 also increments the day of the month.

This method can also be used to set the minutes, seconds and milliseconds.

Browser Support

setHours() Yes Yes Yes Yes Yes

Syntax

dateObject.setHours(hour,min,sec,millisec);




Parameter Values

Parameter Description
hour Required. An integer representing the hour. Expected values are 0-23, but other values are allowed: -1 will be the last hour of the previous day
24 will be the first hour of the next day
min Optional. An integer representing the minutes. Expected values are 0-59, but other values are allowed: -1 will be the last minute of the previous hour
60 will be the first minute of the next hour
sec Optional. An integer representing the seconds Expected values are 0-59, but other values are allowed: -1 will be the last second of the previous minute
60 will be the first second of the next minute
millisec Optional. An integer representing the milliseconds Expected values are 0-999, but other values are allowed: -1 will be the last millisecond of the previous second
1000 will be the first millisecond of the next second




Return Value

return a number, representing the number of milliseconds between the date object and midnight January 1 1970.

Example


      var myDate = new Date();
      
      myDate.setHours(3);
      console.log(myDate.toString());
      

The code above generates the following result.

Example 2

The following code sets the time to 16:36:02


<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {<!--from   w ww  . j  av a 2  s  . co m-->
    var d = new Date();
    d.setHours(16, 36, 2);
    document.getElementById("demo").innerHTML = d;
}
</script>
</body>
</html>

The code above is rendered as follows:

Example 3

The following code sets the time to 24 hours ago:


<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {<!--from   ww  w .  j a  va2  s. c om-->
    var d = new Date();
    d.setHours(d.getHours() - 24);
    document.getElementById("demo").innerHTML = d;
}
</script>
</body>
</html>

The code above is rendered as follows: