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 秒列印一次。

廣告