Date.prototype.setSeconds() 根據**本地時間**設置 Date 對象的**秒數**,可選同時設置毫秒。返回更新後的時間戳(毫秒數)。
dateObj.setSeconds(secondsValue[, msValue])
| 參數 | 範圍 | 說明 |
|---|---|---|
secondsValue | 0-59 | **必填**。秒數 |
msValue | 0-999 | 可選。毫秒數。若提供,必須同時提供 secondsValue |
更新後的時間戳(Number),非 Date 對象。
const dt = new Date('Aug 28, 2008 23:30:00');
console.log('原始:', dt.toString()); // Thu Aug 28 2008 23:30:00 GMT+0800
// 僅設置秒
dt.setSeconds(30);
console.log('setSeconds(30):', dt.toString()); // Thu Aug 28 2008 23:30:30 GMT+0800
// 同時設置秒、毫秒
dt.setSeconds(45, 500);
console.log('setSeconds(45,500):', dt.toString()); // Thu Aug 28 2008 23:30:45.500 GMT+0800
const dt = new Date('2024-01-01 12:00:00');
dt.setSeconds(70); // 70秒 = 1分10秒
console.log(dt.toString()); // 2024-01-01 12:01:10 (分鐘+1)
dt.setSeconds(-10); // -10秒 = 借1分鐘 = 50秒
console.log(dt.toString()); // 2024-01-01 11:59:50 (分鐘-1)
dt.setSeconds(30, 1500); // 1500毫秒 = 1.5秒 → 31秒500毫秒
console.log(dt.toString()); // 2024-01-01 11:59:31.500
function alignToMinute(date = new Date()) {
date.setSeconds(0, 0);
return date;
}
function alignTo10Seconds(date = new Date()) {
const seconds = date.getSeconds();
const aligned = Math.round(seconds / 10) * 10;
date.setSeconds(aligned, 0);
return date;
}
function preciseTimestamp() {
const now = new Date();
// 手動設置毫秒以獲得一致性(如日誌系統)
now.setMilliseconds(0); // 或保留實際毫秒
return now.getTime();
}
// 配合 performance.now() 獲取亞毫秒精度
function highResTimestamp() {
const base = new Date();
base.setMilliseconds(0);
return base.getTime() + performance.now();
}
// 消除 setInterval 累積誤差:每次校準到下一個整秒
function preciseInterval(fn, intervalMs = 1000) {
const nextTick = Date.now() + intervalMs;
const timer = setTimeout(function tick() {
fn();
const now = Date.now();
const drift = now - nextTick;
const nextDelay = intervalMs - drift;
setTimeout(tick, Math.max(0, nextDelay));
}, intervalMs);
return () => clearTimeout(timer);
}
const dt = new Date();
dt.setUTCSeconds(30, 500);
console.log(dt.toISOString()); // UTC 時間反映變化
date.setSeconds(30).setMilliseconds(0) ❌new Date(y, m, d, h, min, sec, ms),避免多次 setter 觸發重算| 方法 | 設置分量 | UTC 版本 |
|---|---|---|
setHours() | 時、分、秒、毫秒 | setUTCHours() |
setMinutes() | 分、秒、毫秒 | setUTCMinutes() |
setSeconds() | 秒、毫秒 | setUTCSeconds() |
setMilliseconds() | 毫秒 | setUTCMilliseconds() |
setTime(ms) | 時間戳(毫秒) | - |
setSeconds() 配合自動進位特性,是實現時間對齊、精確定時、高精度時間戳的基礎工具。現代代碼中常與 Date.now()、performance.now() 結合使用。