JavaScript Date getSeconds() 方法
在 JavaScript 中,Date.getSeconds() 方法用于根据本地时区获取指定日期和时间的秒数部分。返回值是一个介于 0 到 59 之间的整数,指定日期的秒数。
如果我们提供的 Date 对象无效,此方法将返回非数字 (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() 方法从提供的日期中获取秒数部分。
<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 秒打印一次秒数。

