JavaScript Date.setSeconds() 方法用于设置日期对象的 “seconds” 组件。此方法仅影响日期的秒部分,其他部分(如小时、分钟、毫秒)保持不变。此外,我们可以修改 date 对象的 “milliseconds”。
此方法的返回值将是 Date 对象的更新时间戳,它反映了通过修改 seconds 组件所做的更改。如果传递的值大于 59 或小于 0,则会自动相应地调整其他组件。
语法
以下是 JavaScript Date.setSeconds() 方法的语法 -
setSeconds(secondsValue, millisecondsValue);
参数
此方法接受两个参数。下面描述相同 -
- secondsValue − 表示秒数(0 到 59)的整数。
- 如果提供 -1,则会导致前一分钟的最后一秒。
- 如果提供 60,则会导致下一分钟的第一秒。
- millisecondsValue(可选)− 表示毫秒(0 到 999)的整数。
- 如果提供 -1,则会导致前一秒的最后一毫秒。
- 如果提供 1000,则会导致下一秒的第一毫秒。
返回值
此方法返回表示设置新月份后调整后的日期的时间戳。
示例 1
在以下示例中,我们使用 JavaScript Date.setSeconds() 方法将当前 Date 的“秒”设置为 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 GMT+0530 (India Standard Time)”。
示例 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 GMT+0530 (India Standard Time)”。
示例 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 GMT+0530 (India Standard Time)”。