JavaScript Date setHours() 方法



JavaScript 的 Date setHours() 方法用于设置 Date 对象的“小时”部分。它允许根据给定的数值(范围为 0 到 23)更新小时部分。此方法的返回值将是 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() 方法将当前日期的“小时”设置为 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

在这里,我们将“小时”设置为 (10),“分钟”设置为 (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

在这里,我们将“小时”设置为 (10),“分钟”设置为 (30),“秒”设置为 (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>

输出

它返回一个时间戳记,例如“2023年11月20日 星期一 19:00:00 GMT+0530 (印度标准时间)”。

示例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>

输出

它返回一个时间戳记,例如“2023年11月20日 星期一 18:31:00 GMT+0530 (印度标准时间)”。

广告
© . All rights reserved.