Build A Simple Clock Using Js

Posted on May 15, 2025 by Vishesh Namdev
Python C C++ Javascript Java
Build Simple Clock using HTML, CSS and JS

Build a Simple Clock Using JavaScript

The clock will display the current time in 12-hour format. The clock will update every second. The clock will display AM/PM. The clock will display the date. The clock will display the time in seconds, minutes and hours.

What Youโ€™ll Learn

  • How to use setInterval for real-time updates
  • How to work with the Date object in JavaScript
  • How to manipulate the DOM dynamically
  • Final Output

    Your clock will look like this (styling may vary):

    12:45:30 PM

    Step 1: HTML Structure

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Digital Clock</title>
      <style>
        body {
          display: flex;
          justify-content: center;
          align-items: center;
          height: 100vh;
          font-family: 'Arial', sans-serif;
          background-color: #121212;
          color: #ffffff;
        }
        #clock {
          font-size: 60px;
          background: #1e1e1e;
          padding: 30px 60px;
          border-radius: 15px;
          box-shadow: 0 0 15px rgba(255, 255, 255, 0.1);
        }
      </style>
    </head>
    <body>
    
      <div id="clock">--:--:-- --</div>
    
      <script src="clock.js"></script>
    </body>
    </html>

    Step 2: JavaScript Logic

    function updateClock() {
      const now = new Date();
    
      let hours = now.getHours();
      const minutes = now.getMinutes();
      const seconds = now.getSeconds();
    
      const ampm = hours >= 12 ? 'PM' : 'AM';
    
      hours = hours % 12 || 12; // Convert 0 to 12 for 12-hour format
    
      // Pad minutes and seconds with leading zeros if needed
      const formattedTime = 
        `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')} ${ampm}`;
    
      document.getElementById('clock').textContent = formattedTime;
    }
    
    // Initial call
    updateClock();
    
    // Update every second
    setInterval(updateClock, 1000);

    Explanation:

  • new Date(): Gets the current time.
  • getHours(), getMinutes(), getSeconds(): Extracts parts of the time.
  • % 12 || 12: Converts 24-hour format to 12-hour and handles 0 as 12.
  • padStart(2, '0'): Ensures time units have two digits.
  • setInterval(updateClock, 1000): Runs the clock update every second.
  • Note:- You can try this out in a browser or tools like JSFiddle, CodePen, or your own index.html.

    ๐Ÿ“ขImportant Note๐Ÿ“ข

    How did you feel about this post?

    ๐Ÿ˜ ๐Ÿ™‚ ๐Ÿ˜ ๐Ÿ˜• ๐Ÿ˜ก

    Was this helpful?

    ๐Ÿ‘ ๐Ÿ‘Ž