在 JavaScript 中,Date.getSeconds() 方法用于根据本地时区获取指定日期和时间的秒部分。返回值将是介于 (0 到 59) 之间的整数,用于指定日期的秒数。
如果我们提供的 Date 对象无效,则此方法将返回 Not a Number (NaN) 作为结果。
语法
以下是 JavaScript Date.getSeconds() 方法的语法 -
getSeconds();
此方法不接受任何参数。
返回值
此方法返回一个整数,该整数表示 Date 对象的时间部分的秒部分。
示例 1
在以下示例中,我们将演示 JavaScript Date.getSeconds() 方法的基本用法 -
<html>
<body>
<script>
const currentDate = new Date();
const seconds = currentDate.getSeconds();
document.write(seconds);
</script>
</body>
</html>
输出
上述程序根据当地时间返回日期的秒数。
示例 2
在这里,我们使用 getSeconds() 方法从提供的日期获取 seconds 组件。
<html>
<body>
<script>
const specificDate = new Date('December 25, 2023 10:30:45');
const seconds = specificDate.getSeconds();
document.write(seconds);
</script>
</body>
</html>
输出
上面的程序返回整数 45 作为秒值。
示例 3
在这里,我们设置了一个 “setInterval”,它将每 2 秒打印一次本地时间的秒数。
<html>
<body>
<script>
function printSeconds() {
const currentDate = new Date();
const seconds = currentDate.getSeconds();
document.write(seconds + "<br>");
}
setInterval(printSeconds, 2000);
</script>
</body>
</html>
输出
正如我们所看到的,秒数每 2 秒打印一次。