JavaScript Date setUTCSeconds() 方法



JavaScript 的 Date.setUTCSeconds() 方法用于根据协调世界时 (UTC) 设置 Date 对象的“秒”。此方法的返回值将是 Date 对象的更新时间戳,它反映了通过修改秒分量所做的更改。此外,我们还可以修改日期对象的“毫秒”。

UTC,也称为协调世界时,是世界时间标准确定的时间。UTC 等同于格林尼治标准时间 (GMT),确保全球时间测量的统一性。

语法

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

setUTCSeconds(secondsValue, millisecondsValue);

参数

此方法接受两个参数。具体说明如下:

  • secondsValue 表示秒数的整数 (0 到 59)。
    • 如果提供 -1,则结果为前一分钟的最后一秒。
    • 如果提供 60,则结果为下一分钟的第一秒。
  • millisecondsValue (可选) 表示毫秒数的整数 (0 到 999)。
    • 如果提供 -1,则结果为前一秒的最后一毫秒。
    • 如果提供 1000,则结果为下一秒的第一毫秒。

返回值

此方法返回生成的日期与 1970 年 1 月 1 日午夜协调世界时 (UTC) 之间的毫秒数。

示例 1

在下面的示例中,我们使用 JavaScript Date setUTCSeconds() 方法将“秒”设置为 30,根据 UTC 时间:

<html>
<body>
<script>
   const currentDate = new Date();
   currentDate.setUTCSeconds(30);

   document.write(currentDate));
</script>
</body>
</html>

输出

如果我们执行上述程序,秒将设置为 30。

示例 2

如果我们为 secondsValue 提供“-1”,此方法将给出前一分钟的最后一秒:

<html>
<body>
<script>
   const currentDate = new Date("2023-12-25 18:30:10");
   currentDate.setUTCSeconds(-1);

   document.write(currentDate.getUTCSeconds());
</script>
</body>
</html>

输出

它将返回“59”作为前一分钟 (29) 的最后一秒。

示例 3

如果我们为 secondsValue 提供“60”,此方法将给出下一分钟的第一秒:

<html>
<body>
<script>
   const currentDate = new Date("2023-12-25 18:30:10");
   currentDate.setSeconds(60);

   document.write(currentDate.getUTCSeconds());
</script>
</body>
</html>

输出

它将返回“0”作为前一分钟 (31) 的最后一秒。

示例 4

在下面的示例中,我们正在设置日期对象的“毫秒”以及“秒”:

<html>
<body>
<script>
   const currentDate = new Date("2023-12-25 18:30:10");
   currentDate.setSeconds(35, 697);

   document.write("UTCSeconds: ", currentDate.getUTCSeconds(), "
","UTCMilliseconds: ", currentDate.getMilliseconds()); </script> </body> </html>

输出

如果我们执行上述程序,秒将设置为“35”,毫秒设置为“697”。

示例 5

如果我们将 NaN 值作为参数传递给此函数,则日期将设置为“无效日期”,并且返回 NaN 作为结果:

<html>
<body>
<script>
   const currentDate = new Date();
   currentDate.setUTCSeconds("Hle");

   document.write(currentDate);
</script>
</body>
</html>

输出

我们可以看到输出,返回 NaN 作为输出。

广告
© . All rights reserved.