JavaScript Date setUTCSeconds() 方法
JavaScript 的 Date.setUTCSeconds() 方法用于根据协调世界时 (UTC) 设置 Date 对象的"秒"。此方法的返回值将是 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() 方法根据 UTC 时间将"秒"设置为 30。-
<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"。

