JavaScript Date setSeconds() 方法
JavaScript Date.setSeconds() 方法用于设置日期对象的"秒"部分。此方法仅影响日期的秒部分,其他部分(例如小时、分钟、毫秒)保持不变。此外,我们还可以修改日期对象的"毫秒"。
此方法的返回值将是 Date 对象的更新时间戳,该时间戳反映了修改秒部分所做的更改。如果传递的值大于 59 或小于 0,它将自动相应地调整其他部分。
语法
以下是 JavaScript Date setSeconds() 方法的语法 -
setSeconds(secondsValue, millisecondsValue);
参数
此方法接受两个参数。具体说明如下:-
-
secondsValue - 一个表示秒数的整数(0 到 59)。
- 如果提供 -1,则返回上一分钟的最后一秒。
- 如果提供 60,则返回下一分钟的第一秒。
-
millisecondsValue (可选) - 一个表示毫秒数的整数(0 到 999)。
- 如果提供 -1,则返回前一秒的最后一毫秒。
- 如果提供 1000,则返回下一秒的第一毫秒。
返回值
此方法返回设置新月份后表示调整后日期的时间戳。
示例 1
在下面的示例中,我们使用 JavaScript Date 的 setSeconds() 方法将当前日期的"秒数"设置为 30 −
<html> <body> <script> const currentDate = new Date(); currentDate.setSeconds(30); document.write(currentDate); </script> </body> </html>
输出
如果我们执行上述程序,秒数将被设置为 30。
示例 2
在这里,我们将在指定日期上添加 15 秒 -
<html>
<body>
<script>
const currentDate = new Date("2023-12-25 18:30:10");
currentDate.setSeconds(currentDate.getSeconds() + 15);
document.write(currentDate);
</script>
</body>
</html>
输出
它将返回一个时间戳,如下所示 "Mon Dec 25 2023 18:30:25".
示例 3
如果我们为secondsValue提供"-1",则此方法将返回前一分钟的最后一秒 -
<html>
<body>
<script>
const currentDate = new Date("2023-12-25 18:30:10");
currentDate.setSeconds(-1);
document.write(currentDate);
</script>
</body>
</html>
输出
它将返回一个时间戳,如下所示 "Mon Dec 25 2023 18:29:59".
示例 4
如果我们为secondsValue提供"60",则此方法将返回下一分钟的第一秒 -
<html>
<body>
<script>
const currentDate = new Date("2023-12-25 18:30:10");
currentDate.setSeconds(60);
document.write(currentDate);
</script>
</body>
</html>
输出
它将返回一个时间戳,如下所示 "Mon Dec 25 2023 18:31:00".

