JavaScript Date setUTCHours() 方法



JavaScript 的 Date.setUTCHours() 方法用于根据协调世界时 (UTC) 设置 Date 对象的小时。此外,我们还可以设置分钟、秒和毫秒(可选)。

UTC 代表协调世界时。它是世界各地用来调节时钟和时间的首要时间标准。而印度标准时间 (IST) 是印度采用的时间,IST 和 UTC 的时差为 UTC+5:30(即 5 小时 30 分钟)。

语法

以下是 JavaScript Date setUTCHours() 方法的语法:

setUTCHours(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,则结果为下一秒的第一毫秒。

返回值

此方法返回 1970 年 1 月 1 日午夜与更新的日期和时间之间的毫秒数。

示例 1

在以下示例中,我们使用 JavaScript Date setUTCHours() 方法将小时设置为 10,根据 UTC 时间:

<html>
<body>
<script>
   const currentDate = new Date();
   currentDate.setUTCHours(10);

   document.write('Updated Date:  ', currentDate);
</script>
</body>
</html>

输出

此程序返回比 10 小时 (UTC) 快 5 小时的時間。分钟不会提前 30 分钟,因为我们这里没有设置分钟。

示例 2

在这里,我们将小时设置为 12(根据 UTC),并使用 getUTCHours() 方法返回它:

<html>
<body>
<script>
   const currentDate = new Date("December 25, 2023, 10:15:00");
   currentDate.setUTCHours(12);

   document.write('Updated UTC hour:  ', currentDate.getUTCHours());
</script>
</body>
</html>

输出

上述程序返回 12 作为小时。

示例 3

在这里,我们为 Date 对象提供了一个具体的日期。然后,我们将小时设置为 15,根据 UTC 时间:

<html>
<body>
<script>
   const currentDate = new Date("December 25, 2023, 10:15:00");
   currentDate.setUTCHours(15); // Set the hours to 20 (According to UTC)

   document.write("Updated Date:  ", currentDate);
</script>
</body>
</html>

输出

此程序返回比 15 小时 (UTC) 快 5 小时的時間。分钟不会提前 30 分钟,因为我们这里没有设置分钟。

示例 4

在下面的示例中,我们将小时设置为 11,分钟设置为 30,根据 UTC:

<html>
<body>
<script>
   const currentDate = new Date("December 25, 2023, 10:15:00");
   currentDate.setUTCHours(11, 30); // Set the hours to 11 and the minutes to 30 (According to UTC)

   document.write("Updated Date:  ", currentDate);
</script>
</body>
</html>

输出

此程序返回比 11 小时 30 分钟 (UTC) 快 5 小时 30 分钟的时间。

示例 5

在这里,我们根据 UTC 设置小时、分钟和秒:

<html>
<body>
<script>
   const currentDate = new Date("December 25, 2023, 10:15:00");
   currentDate.setUTCHours(11, 20, 30); 

   document.write("Updated Date:  ", currentDate);
</script>
</body>
</html>

输出

上述程序将返回“Mon Dec 25 2023 16:50:30 GMT+0530 (India Standard Time)”作为输出。

广告
© . All rights reserved.