<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>動態時鐘範例</title>
<script type="text/javascript">
// 取得格式化時間字串
function getCurrentTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1; // 0-11
var day = now.getDate();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
// 補零函式
var pad = function(n) { return n < 10 ? '0' + n : n; };
return year + '/' + pad(month) + '/' + pad(day) + ' ' +
pad(hours) + ':' + pad(minutes) + ':' + pad(seconds);
}
// 每秒更新一次
setInterval(function() {
document.getElementById('ht').innerHTML = getCurrentTime();
}, 1000);
</script>
</head>
<body>
<span id="ht"></span> <!-- 顯示時間的容器 -->
</body>
</html>
Date 物件方法:getFullYear()、getMonth() (0-11 需 +1)、getDate()、getHours()、getMinutes()、getSeconds()。09:05:03)。setInterval(fn, 1000):每 1000ms (1秒) 執行一次更新。innerHTML 更新顯示,簡單高效。function formatDate(date, options) {
options = options || {};
var fmt = options.format || 'YYYY/MM/DD HH:mm:ss';
var is12h = options.hour12 || false;
var tzOffset = options.timezoneOffset || 0; // 分鐘
// 套用時區偏移
var d = new Date(date.getTime() + tzOffset * 60000);
var h = d.getUTCHours();
var meridiem = '';
if (is12h) {
meridiem = h >= 12 ? ' PM' : ' AM';
h = h % 12 || 12;
}
var pad = function(n) { return n < 10 ? '0' + n : n; };
return fmt
.replace('YYYY', d.getUTCFullYear())
.replace('MM', pad(d.getUTCMonth() + 1))
.replace('DD', pad(d.getUTCDate()))
.replace('HH', pad(h))
.replace('mm', pad(d.getUTCMinutes()))
.replace('ss', pad(d.getUTCSeconds()))
.replace('A', meridiem.trim());
}
// 使用範例
setInterval(function() {
document.getElementById('ht').innerHTML = formatDate(new Date(), { hour12: true });
}, 1000);
動態時鐘是 JS 入門經典練習,掌握 Date API、字串格式化、定時器三大核心概念。