Digital Clock JavaScript Code

Here's an example of a simple JavaScript digital clock that displays the current time on a webpage:

<div id="clock"></div>

<script>
  function updateClock() {
    var currentTime = new Date();
    var currentHours = currentTime.getHours();
    var currentMinutes = currentTime.getMinutes();
    var currentSeconds = currentTime.getSeconds();
    
    // Add leading zeros to minutes and seconds
    currentMinutes = (currentMinutes < 10 ? "0" : "") + currentMinutes;
    currentSeconds = (currentSeconds < 10 ? "0" : "") + currentSeconds;
    
    // Choose AM or PM
    var timeOfDay = (currentHours < 12) ? "AM" : "PM";
    
    // Convert hours from military time
    currentHours = (currentHours > 12) ? currentHours - 12 : currentHours;
    
    // Set hours to 12 if it's 0
    currentHours = (currentHours == 0) ? 12 : currentHours;
    
    // Set the clock's text
    var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;
    document.getElementById("clock").innerHTML = currentTimeString;
  }
  
  setInterval(updateClock, 1000);
</script>

This code creates a div element with an id of "clock" that will be used to display the time. The updateClock() function is called every 1000 milliseconds (1 second) by the setInterval() function. This function uses the Date() object to get the current time, and then formats it as a string with hours, minutes, and seconds. It also adds an "AM" or "PM" to the end of the time, depending on the current hours. The formatted time is then displayed within the "clock" div element.

You can use this code as a base and customize it to fit your needs and design.

Next Post Previous Post
No Comment
Add Comment
comment url