萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 實作網頁即時動態時鐘 (年/月/日 時:分:秒)

核心程式碼

<!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>

關鍵點解析

  1. Date 物件方法:getFullYear()、getMonth() (0-11 需 +1)、getDate()、getHours()、getMinutes()、getSeconds()。
  2. 補零處理:個位數時前面補 '0',確保格式固定寬度 (如 09:05:03)。
  3. setInterval(fn, 1000):每 1000ms (1秒) 執行一次更新。
  4. 直接操作 innerHTML 更新顯示,簡單高效。

進階擴充:支援多時區 / 12小時制

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、字串格式化、定時器三大核心概念。

copyright © 萬盛學電腦網 all rights reserved