JavaScript Date.setUTCSeconds() 方法用于根据协调世界时 (UTC) 设置 Date 对象的“秒”。此方法的返回值将是 Date 对象的更新时间戳,它反映了通过修改 seconds 组件所做的更改。此外,我们可以修改 date 对象的 “milliseconds”。
UTC,也称为协调世界时,是由世界时间标准确定的时间。UTC 相当于 GMT(格林威治标准时间),确保了全球时间测量的一致性。
语法
以下是 JavaScript Date.setUTCSeconds() 方法的语法 -
setUTCSeconds(secondsValue, millisecondsValue);
参数
此方法接受两个参数。下面描述相同 -
- secondsValue一个整数,表示秒数(0 到 59)。
- 如果提供 -1,则会导致前一分钟的最后一秒。
- 如果提供 60,则会导致下一分钟的第一秒。
- millisecondsValue (可选)一个整数,表示毫秒(0 到 999)。
- 如果提供 -1,则会导致前一秒的最后一毫秒。
- 如果提供 1000,则会导致下一秒的第一毫秒。
返回值
此方法返回生成日期与世界协调时 (UTC) 1970 年 1 月 1 日午夜之间的毫秒数。
示例 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
在下面的示例中,我们将 date 对象的 “milliseconds” 与 “seconds” 一起设置 -
<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” 作为输出返回。