Date.prototype.setSeconds()

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

setSeconds() 方法用於 Date 例項,根據本地時間更改此日期的秒和/或毫秒。

試一試

const event = new Date("August 19, 1975 23:15:30");

event.setSeconds(42);

console.log(event.getSeconds());
// Expected output: 42

console.log(event);
// Expected output: "Sat Apr 19 1975 23:15:42 GMT+0100 (CET)"
// Note: your timezone may vary

語法

js
setSeconds(secondsValue)
setSeconds(secondsValue, msValue)

引數

secondsValue

一個介於 0 和 59 之間的整數,表示秒。

msValue 可選

一個介於 0 和 999 之間的整數,表示毫秒。

返回值

該方法會直接修改 Date 物件,並返回其新的 時間戳。如果某個引數是 NaN(或被 強制轉換NaN 的值,如 undefined),則日期將設定為 無效日期,並返回 NaN

描述

如果您不指定 msValue 引數,則會使用從 getMilliseconds() 方法返回的值。

如果您指定的引數超出了預期範圍,setSeconds() 會嘗試相應地更新 Date 物件中的日期資訊。例如,如果您為 secondsValue 使用 100,則 Date 物件中儲存的分鐘數將增加 1,秒數將使用 40。

由於 setSeconds() 操作的是本地時間,因此跨越夏令時 (DST) 邊界可能會導致經過的時間與預期不同。例如,如果設定的秒數跨越了春季向前調整(損失一小時),則新舊日期之間的時間戳差異將比名義時間差少一個小時。反之,跨越秋季向後調整(增加一小時)將導致多出一個小時。如果您需要按固定時間量調整日期,請考慮使用 setUTCSeconds()setTime()

如果新的本地時間落在偏移量轉換範圍內,則確切時間將使用與 Temporaldisambiguation: "compatible" 選項相同的行為來確定。也就是說,如果本地時間對應兩個瞬間,則選擇較早的那個;如果本地時間不存在(存在間隙),則向前推進間隙持續的時間。

示例

使用 setSeconds()

js
const theBigDay = new Date();
theBigDay.setSeconds(30);

規範

規範
ECMAScript® 2026 語言規範
# sec-date.prototype.setseconds

瀏覽器相容性

另見