JavaScript Digital Clock Code

Javascript Digital Clock Code
Project: Digital Clock In JavaScript
Author: Aaron Farrar
Edit Online: View on CodePen
License: MIT

This JavaScript code snippet helps you to create a digital clock. It defines a function called “showTime” that displays the current time on a web page. It gets the current time using the JavaScript Date object and extracts the hours, minutes, and seconds. Then, formats the time as a string with hours, minutes, seconds, and AM or PM indicators. Finally, the function then updates the time in DOM with the formatted time string.

The clock UI comes with a simple and clean design that displays real-time updating seconds. However, the clock widget can be customized with additional CSS according to your needs.

How to Integrate JavaScript Code to Create Digital Clock

First of all, load the Normalize CSS, Google Fonts, and PrefixFree JS by adding the following CDN link into the head tag of your HTML document.

<link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Orbitron'> 
<link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Aldrich'> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>

Now, Create a div element with an id “MyClockDisplay”, set its class “clock” and call the showTime() function with onload attribute.

<div id="MyClockDisplay" class="clock" onload="showTime()"></div>

Style the digital clock using the following CSS styles. You can change the CSS values in order to customize the clock widget according to your needs.

body {
    background: black;
}

.clock {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
    color: #17D4FE;
    font-size: 60px;
    font-family: Orbitron;
    letter-spacing: 7px;
   background-color: black;
padding: 30px;
width: 80%;
height: 80%;
margin: 0 auto;
}

Finally, add the following JavaScript function to activate the clock:

function showTime(){
    var date = new Date();
    var h = date.getHours(); // 0 - 23
    var m = date.getMinutes(); // 0 - 59
    var s = date.getSeconds(); // 0 - 59
    var session = "AM";
    
    if(h == 0){
        h = 12;
    }
    
    if(h > 12){
        h = h - 12;
        session = "PM";
    }
    
    h = (h < 10) ? "0" + h : h;
    m = (m < 10) ? "0" + m : m;
    s = (s < 10) ? "0" + s : s;
    
    var time = h + ":" + m + ":" + s + " " + session;
    document.getElementById("MyClockDisplay").innerText = time;
    document.getElementById("MyClockDisplay").textContent = time;
    
    setTimeout(showTime, 1000);
    
}

showTime();

That’s all! hopefully, you have successfully integrated this digital clock into your project.  If you have any questions or suggestions, feel free to comment below.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply