🇯🇵 日本語 | 🇺🇸 English | 🇪🇸 Español | 🇵🇹 Português | 🇹🇭 ไทย | 🇨🇳 中文

[JS] 数字时钟(24小时制)模板

如何使用 JavaScript 实时显示当前时间

⏰ 此模板的使用场景和优点

👇 这个 👇
--:--:--

📋 复制并使用代码


      <!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>当前时间显示</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      text-align: center;
      padding: 20px;
      background-color: #f0f0f0;
    }
    #clock {
      font-size: 3rem;
      font-weight: bold;
      color: #333;
    }
  </style>
</head>
<body>

  <h1>当前时间</h1>
  <div id="clock">--:--:--</div> <!-- 初始值设置为 "--:--:--" -->

  <script>
    setInterval(() => {
      const now = new Date();
      const hh = now.getHours().toString().padStart(2, '0'); // 小时
      const mm = now.getMinutes().toString().padStart(2, '0'); // 分钟
      const ss = now.getSeconds().toString().padStart(2, '0'); // 秒
      document.getElementById("clock").textContent = `${hh}:${mm}:${ss}`; // 显示时间
    }, 1000); // 每秒更新
  </script>

</body>
</html>

    

🧩 應用與進階小技巧

本範本使用 setInterval(() => {...}, 1000) 每秒更新一次目前時間,實現即時顯示效果,無需重新整理頁面。非常適合用於商店櫥窗、數位公告板或需要即時時鐘的網頁應用。

此外,padStart(2, '0') 方法可自動補零,確保時間顯示始終為雙位數格式,例如 09:05:01,而非 9:5:1。

💡 進階技巧

若想顯示上午/下午(AM/PM),可以根據 getHours() 的值來判斷。同時也可以搭配 getFullYear()getDay() 來顯示日期或星期幾。

你也可以使用 CSS 自訂時鐘的外觀,例如背景色、字體大小或字型,以符合你網站的整體設計風格。