日期setHours()方法以及JavaScript中的示例

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值