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 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)” 。

廣告