Home »
JavaScript
Date setHours() method with example in JavaScript
JavaScript Date setHours() method: Here, we are going to learn about the setHours() method in JavaScript with example.
Submitted by IncludeHelp, on March 13, 2019
JavaScript Date setHours() method
setHours() method is a Date class method, it is used to set the hour to the Date object with a valid hour value (between 00 to 23).
Note: Hour value larger than the 23 will be truncated from the starting hour value (0), for example, we are going to set 26 as an hour value, it will be truncated as 2.
Syntax
var dt = new Date();
dt.setHours(hour);
Sample Input/Output
Input/Date class object declaration:
var dt = new Date();
Function call to set the hour:
dt.setHours(16);
Function call to get the hour:
dt.getHours();
Output:
16
JavaScript code to demonstrate an example of Date.setHours() method
<html>
<head><title>JavaScipt Example</title></head>
<body>
<script>
var dt = new Date();
//getting current hour
var hour = dt.getHours();
//printing
document.write("hour: " + hour + "<br>");
//setting hour to 16
dt.setHours(16);
//getting & printing hour again
hour = dt.getHours();
document.write("hour: " + hour + "<br>");
//setting invalid hour
//setting hour to 26
dt.setHours(26);
//getting & printing hour again
hour = dt.getHours();
document.write("hour: " + hour + "<br>");
</script>
</body>
</html>
Output
hour: 19
hour: 16
hour: 2
Reference: JavaScript setHours() Method
JavaScript Date Object Methods »