/**
* 日期時間顯示組件
* @param {HTMLElement|string} dateEl - 日期顯示元素
* @param {HTMLElement|string} timeEl - 時間顯示元素
*/
class DateTimeDisplay {
constructor(dateEl, timeEl, options = {}) {
this.dateEl = typeof dateEl === 'string' ? document.querySelector(dateEl) : dateEl;
this.timeEl = typeof timeEl === 'string' ? document.querySelector(timeEl) : timeEl;
this.options = {
locale: 'zh-CN',
dateFormat: 'YYYY年MM月DD日 dddd',
timeFormat: 'HH:mm:ss',
interval: 1000,
...options
};
this.timer = null;
this._init();
}
_init() {
if (!this.dateEl || !this.timeEl) {
console.warn('DateTimeDisplay: 元素未找到');
return;
}
this._update();
this.timer = setInterval(() => this._update(), this.options.interval);
}
_update() {
const now = new Date();
const locale = this.options.locale;
// 使用 Intl 原生格式化(推薦)
if (this.options.useIntl !== false) {
try {
this.dateEl.textContent = new Intl.DateTimeFormat(locale, {
year: 'numeric', month: '2-digit', day: '2-digit', weekday: 'long'
}).format(now).replace(/\//g, '年').replace(/\//g, '月').replace(/日/, '日 ');
this.timeEl.textContent = new Intl.DateTimeFormat(locale, {
hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false
}).format(now);
return;
} catch (e) {
// 降級到手動格式化
}
}
// 手動格式化降級
const pad = n => String(n).padStart(2, '0');
const week = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'][now.getDay()];
this.dateEl.textContent = `${now.getFullYear()}年${pad(now.getMonth()+1)}月${pad(now.getDate())}日 ${week}`;
this.timeEl.textContent = `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;
}
stop() { clearInterval(this.timer); this.timer = null; }
destroy() { this.stop(); this.dateEl = this.timeEl = null; }
}
// 自動初始化:data-datetime="dateElSelector,timeElSelector"
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('[data-datetime]').forEach(el => {
const [dateSel, timeSel] = el.dataset.datetime.split(',');
new DateTimeDisplay(dateSel, timeSel);
});
});
<!-- 方式一:自動掛載(推薦) -->
<div data-datetime="#dateEl,#timeEl">
<span id="dateEl" class="datetime-date"></span>
<span id="timeEl" class="datetime-time"></span>
</div>
<!-- 方式二:手動實例化 -->
<input type="text" id="dateInput" readonly class="datetime-input">
<input type="text" id="timeInput" readonly class="datetime-input">
<script>
new DateTimeDisplay('#dateInput', '#timeInput', { useIntl: true });
</script>
<style>
.datetime-date { font-weight: 500; color: #2c3e50; }
.datetime-time { font-family: 'Monospace', monospace; font-variant-numeric: tabular-nums; color: #e74c3c; }
.datetime-input { border: none; background: transparent; font-size: 1rem; outline: none; }
</style>
| 項目 | 舊寫法問題 | 現代最佳實踐 |
|---|---|---|
| 年份 | getYear() 返回 124 (2024-1900) | getFullYear() 返回 2024 |
| 月份 | 0-11 需手動 +1 | 同樣需 +1,但用 padStart 補零 |
| 補零 | if(m<10) m='0'+m | String(m).padStart(2,'0') |
| 定時器 | setTimeout(遞歸) 累積誤差 | setInterval 固定間隔 |
| 格式化 | 字符串拼接易錯 | Intl.DateTimeFormat 國際化標準 |
| XSS | innerHTML 直接賦值 | textContent / value 安全 |
| 內存 | 頁面卸載未清理 | 組件化 destroy() 釋放 |
_update = () => {
if (document.hidden) return; // 頁面隱藏不更新
// ... 更新邏輯
};
// 頁面可見性變化恢復
document.addEventListener('visibilitychange', () => {
if (!document.hidden && this.timer) this._update(); // 立即同步一次
});
將日期時間顯示封裝為 DateTimeDisplay 類,配合 Intl.DateTimeFormat 原生國際化格式化、padStart 補零、setInterval 固定頻率、textContent 安全輸出、組件生命周期管理,即可得到生產級可復用組件。避免古老的 getYear()、手動拼接、innerHTML、遞歸 setTimeout 等易錯模式。