function Format2Len(i) {
return i < 10 ? "0" + i : i; // 單位數補零
}
function RefreshClock() {
var CurrentTime = new Date();
var timeStr = CurrentTime.getFullYear() + "-" +
Format2Len(CurrentTime.getMonth() + 1) + "-" +
Format2Len(CurrentTime.getDate()) + " " +
Format2Len(CurrentTime.getHours()) + ":" +
Format2Len(CurrentTime.getMinutes()) + ":" +
Format2Len(CurrentTime.getSeconds());
txtClock.value = timeStr;
}
setInterval("RefreshClock()", 1000); // 每秒更新
| 方法 | 返回值 | 注意 |
|---|---|---|
getFullYear() | 四位年份 | |
getMonth() | 0-11 | 需 +1 得到實際月份 |
getDate() | 1-31 | 當月日期 |
getHours() | 0-23 | 24小時制 |
getMinutes() | 0-59 | |
getSeconds() | 0-59 |
// 等價於
if (i < 10) { return "0" + i; } else { return i; }
簡潔且無副作用,適合格式化數字。
<body onload="RefreshClock()">
當前時間:<input type="text" id="txtClock" />
</body>
onload 確保頁面載入即顯示時間,setInterval 後續每秒刷新。
toLocaleTimeString() / toLocaleDateString() 自動本地化格式。Intl.DateTimeFormat 精確控制輸出格式。requestAnimationFrame 配合 performance.now() 減少定時器誤差。<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>數字時鐘</title></head>
<body>
<div id="clock" style="font: 24px monospace;"></div>
<script>
const el = document.getElementById('clock');
function update() {
const now = new Date();
el.textContent = now.toLocaleTimeString('zh-CN', { hour12: false });
}
update();
setInterval(update, 1000);
</script>
</body></html>