JS - Digital Clock Display

create a digital clock using simple Javascript and a little bit of CSS for styling


Tuts Library »

Digital Clock Display

Using a bit of Javascript and CSS to create and style a digital clock. You can see the finished product below. See Countdown Timer using the same code but with a twist!

JS Digital Clock

Current Time

How It's Done

HTML:

<div id="clockArea">
   <h2>JS Digital Clock</h2>
   <div id="clockDisplay" class="clockStyle"></div>
   <h3>Current Time</h3>
</div>
<script type="text/javascript">renderTime();</script>
               

CSS:

#clockArea {
   text-align: center;
   border: 2px solid #000;
   outline: 1px solid #444;
   box-shadow: inset 0px 0px 8px rgba(0,0,0,0.4);
   background-color: #666;
   width: 250px;
   height: 175px;
}
#clockArea > h2 {
   margin-bottom: 35px;
   color: #73DCFF;
}
.clockStyle {
   font-family: "Lucidia Sans";
   background-color: #000;
   border: 3px solid #444;
   outline: 1px solid #000;
   box-shadow: inset 0px 0px 5px rgba(0,0,0,0.3);
   padding: 6px;
   font-size: 18px;
   letter-spacing: 2px;
   font-weight: bold;
   color: #73DCFF;
   display: inline;
}               
               

Javascript:

               

Create a variable am_pm to render either AM or PM and assign today's date to currentTime

function renderTime() {
   var am_pm = "AM";
   var currentTime = new Date();

Use the functions getHours; getMinutes; getSeconds and assign them each to a variable.

   var h = currentTime.getHours();
   var m = currentTime.getMinutes();
   var s = currentTime.getSeconds();

Use if statements to render the time from military format to a 12-hour format

   if (h == 0) {
      h = 12;
   } else if (h > 12) {
      h = h - 12;
      am_pm = ”PM“
   }

If any section of time is less than 10, we need to prepend a ”0“

   if (h < 10) {
      h = "0" + h;
   }				
   if (m < 10) {
      m = ”0“ + m;
   }		
   if (s < 10) {
      s = ”0“ + s;
   }

Create variable myClockto insert the calculated time into the web page

   var myClock = document.getElementById('clockDisplay').textContent = h+':'+m+':'+s+' '+am_pm;

Use setTimeout to call the function renderTime() every second.

   setTimeout('renderTime()',1000);
}