JavaScript Date.setHours() 方法用于设置 Date 对象的 “hour” 组件。它允许根据给定的数值(可以在 0 到 23 的范围内)更新 hours 组件。此方法的返回值将是 Date 对象的更新时间戳,它反映了通过修改 hour 组件所做的更改。
此外,我们可以修改 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); // Set the hours to 20
document.write("Updated Date:", currentDate);
</script>
</body>
</html>
输出
如果我们执行上述程序,小时将设置为 20,分钟和秒将按照当地时间。
示例 2
在这里,我们将 “hours” 设置为 (10),将 “minutes” 设置为 (30) -
<html>
<body>
<script>
const currentDate = new Date();
currentDate.setHours(10, 30); // Set the hours to 10 and the minutes to 30
document.write("Updated Date:", currentDate);
</script>
</body>
</html>
输出
执行后,此程序将返回包含提供的小时数和分钟数的时间戳。秒数将按照当地时间为准。
示例 3
在这里,我们将 “hours” 设置为 (10),将 “minutes” 设置为 (30),将 “seconds” 设置为 (45) -
<html>
<body>
<script>
const currentDate = new Date();
currentDate.setHours(10, 30, 45); // Set the hours to 10, minutes to 30, and seconds to 45
document.write("Updated Date:", currentDate);
</script>
</body>
</html>
输出
它返回的时间戳为“Wed Dec 27, 2023 10:30:45 GMT+0530 (India Standard Time)”。
示例 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 GMT+0530 (India Standard Time)”。
示例 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 GMT+0530 (India Standard Time)”。
示例 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 GMT+0530 (India Standard Time)”。