JavaScript Date setHours() 方法
JavaScript Date 的 setHours() 方法用于设置 Date 对象的"小时"部分。该方法允许根据给定的数值更新小时部分,该数值的范围为 0 到 23。该方法的返回值将是 Date 对象的更新时间戳,反映修改小时部分后所做的更改。
此外,我们还可以修改 Date 对象的分钟、秒和毫秒。该方法不会返回新的 Date 对象,而是更新调用该方法时所针对的现有 Date 对象。
语法
以下是 JavaScript Date 的 setHours() 方法的语法 -
setHours(hoursValue, minutesValue, secondsValue, millisecondsValue);
参数
此方法接受四个参数。具体说明如下:-
-
hoursValue - 表示小时的整数(0 到 23)。
- 如果提供 -1,则返回前一天的最后一个小时。
- 如果提供 24,则返回后一天的第一个小时。
-
minutesValue (可选) - 表示分钟的整数(0 到 59)。如果未提供,分钟将设置为 0。
- 如果提供 -1,则结果为上一小时的最后一分钟。
- 如果提供 60,则结果为下一小时的第一分钟。
-
secondsValue(可选) − 表示秒数的整数(0 到 59)。如果未提供,秒将设置为 0。
- 如果提供 -1,则结果为上一分钟的最后一秒。
- 如果提供 60,则结果为下一分钟的第一秒。
-
millisecondsValue(可选) − 表示毫秒的整数(0 到 999)。如果未提供,毫秒将被设置为 0。
- 如果提供 -1,则返回前一秒的最后一毫秒。
- 如果提供 1000,则返回下一秒的第一毫秒。
返回值
此方法返回设置指定小时、分钟、秒和毫秒后修改后的 Date 对象的时间戳(以毫秒为单位)。
示例 1
在下面的示例中,我们使用 JavaScript Date 的 setHours() 方法将当前 Date 的"小时"设置为 20 -
<html>
<body>
<script>
const currentDate = new Date();
currentDate.setHours(20); // 将小时数设置为 20
document.write("Updated Date:", currentDate);
</script>
</body>
</html>
输出
如果我们执行上述程序,小时将设置为 20,分钟和秒将根据当地时间。
示例 2
在这里,我们将"小时"设置为 (10),"分钟"设置为 (30) -
<html>
<body>
<script>
const currentDate = new Date();
currentDate.setHours(10, 30); // 将小时设置为 10,分钟设置为 30
document.write("Updated Date:", currentDate);
</script>
</body>
</html>
输出
执行后,该程序将返回一个包含指定小时和分钟的时间戳。秒数将根据当地时间计算。
示例 3
在这里,我们将"小时"设置为 (10),"分钟"设置为 (30),"秒"设置为 (45) -
<html>
<body>
<script>
const currentDate = new Date();
currentDate.setHours(10, 30, 45); // 将小时设置为 10,分钟设置为 30,秒设置为 45
document.write("Updated Date:", currentDate);
</script>
</body>
</html>
输出
它返回一个时间戳,如下所示 "Wed Dec 27 2023 10:30:45".
示例 4
如果我们为 hoursValue 提供"-1",此方法将返回前一天的最后一小时 -
<html>
<body>
<script>
const currentDate = new Date('2023-11-20 15:00:00'); //November 20 2023
currentDate.setHours(-1);
document.write("Updated Date: ", currentDate);
</script>
</body>
</html>
输出
它返回一个时间戳,如下所示 "Sun Nov 19 2023 23:00:00".
示例 5
如果我们为 minutesValue 提供"60",此方法将返回下一个小时的第一分钟 -
<html>
<body>
<script>
const currentDate = new Date('2023-11-20 15:00:00'); //November 20 2023
currentDate.setHours(18, 60);
document.write("Updated Date: ", currentDate);
</script>
</body>
</html>
输出
它返回一个时间戳,如下所示 "Mon Nov 20 2023 19:00:00".
示例 6
如果我们为secondsValue提供"60",则此方法将返回下一分钟的第一秒 -
<html>
<body>
<script>
const currentDate = new Date('2023-11-20 15:00:00'); //November 20 2023
currentDate.setHours(18, 30, 60);
document.write("Updated Date: ", currentDate);
</script>
</body>
</html>
输出
它返回一个时间戳,如下所示 "Mon Nov 20 2023 18:31:00".

