瀏覽器 Date 物件只能取得「當前」時間。要實現從指定時間(如 2025-12-31 23:59:59)開始走動的時鐘,核心邏輯是:
offset)。setInterval 取得最新系統時間,加上 offset 得到「模擬時間」。class CustomClock {
constructor(targetDateString) {
// 1. 解析目標時間 (支援 ISO 8601 格式: "2025-12-31T23:59:59")
this.targetTime = new Date(targetDateString).getTime();
if (isNaN(this.targetTime)) throw new Error('Invalid date format');
// 2. 計算初始偏移量
this.offset = this.targetTime - Date.now();
this.timerId = null;
}
start(selector) {
const el = document.querySelector(selector);
if (!el) return;
const tick = () => {
// 3. 每次取最新系統時間 + 固定偏移 = 模擬時間
const simulated = new Date(Date.now() + this.offset);
el.textContent = this.format(simulated);
};
tick(); // 立即顯示一次
this.timerId = setInterval(tick, 1000);
}
stop() {
if (this.timerId) clearInterval(this.timerId);
}
format(date) {
const pad = n => String(n).padStart(2, '0');
return `${date.getFullYear()}年${pad(date.getMonth()+1)}月${pad(date.getDate())}日 ` +
`${pad(date.getHours())}時${pad(date.getMinutes())}分${pad(date.getSeconds())}秒`;
}
}
// 使用範例
const clock = new CustomClock('2025-12-31T23:59:59');
clock.start('#clock-display');
若不想用字串解析,可直接用 new Date(year, monthIndex, day, hour, minute, second):
// 注意:monthIndex 為 0-11 (0=一月)
const target = new Date(2025, 11, 31, 23, 59, 59); // 2025-12-31 23:59:59
長時間運行會有幾毫秒誤差,進階版可每分鐘透過 NTP 或伺服器 API 校準 offset。
若需「倒數至目標時間」,邏輯改為 const diff = targetTime - Date.now(),判斷 diff <= 0 則停止並觸發回呼。