JavaScript Date setHours()方法 (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).
setHours()方法是Date類方法,用于將小時設置為具有有效小時值(介于00到23之間)的Date對象。
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.
注意:大于23的小時值將從開始的小時值(0)開始被截斷,例如,我們將26設置為小時值,它將被截斷為2。
Syntax:
句法:
var dt = new Date();
dt.setHours(hour);
Examples:
例子:
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
JavaScript代碼演示Date.setHours()方法的示例
<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 setHours()方法
翻譯自: https://www.includehelp.com/code-snippets/date-setHours-method-with-example-in-javascript.aspx