Creating a JavaScript Clock

Use JavaScript's Date object and Window.setInterval method to make a simple real-time clock that you can place on any Web page. Along the way, you take a look at how to access text nodes in the DOM, and how to set an onLoad event handler.

One of the great things about JavaScript is that it lets you manipulate the contents of a Web page in real-time. This means that we can use JavaScript to create a digital clock, embedded in the Web page, that updates every second. This article shows you how to do just that.

Getting the current time

If we want to create a clock then obviously we need to retrieve the current time. We can do this via JavaScript's Date class. First, we create a new Date object with no parameters, which gives us a Date object containing the current date and time on the visitor's computer:


var currentTime = new Date ( );

Next, we extract the hours, minutes and seconds components of the current time from our Date object:


var currentHours = currentTime.getHours ( );
var currentMinutes = currentTime.getMinutes ( );
var currentSeconds = currentTime.getSeconds ( );

Formatting the time

Now that we have the three component values of our current time, let's format them into a nice string for displaying in the Web page. We want it to be in the format "HH:MM:SS XX", where XX is either "AM" or "PM" (assuming we're after a 12-hour clock format).

First we'll add a leading zero to the minutes and seconds values, if required:


currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;

The ? and : symbols used above comprise the ternary operator. This is a special operator that returns the value before the colon if the condition before the query (?) is true, or the value after the colon if the condition is false. It's a great way to write an if block in shorthand, provided you only need to return a single value.

Next we'll set a variable, timeOfDay, to "AM" or "PM" as appropriate, and subtract 12 from the hours component, if required, to convert it to 12-hour format. We'd also like the hours component to show 12 rather than 0, so we need to add a check for this too:


var timeOfDay = ( currentHours < 12 ) ? "AM" : "PM";
currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours;
currentHours = ( currentHours == 0 ) ? 12 : currentHours;

Finally, we'll join all our formatted components together into a single string, in the format "HH:MM:SS XX":


var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;

Displaying the clock

Now that we have our time string ready for display, the next step is to display it in the Web page. To do this, we first create a span container in the markup to hold the time display:


<span id="clock">&nbsp;</span>

By placing the &nbsp; inside the span element, we're creating a child text node for the span in the DOM. We can then populate the container with our time string by retrieving this child text node then setting its nodeValue property, as follows:


document.getElementById("clock").firstChild.nodeValue = currentTimeString;

Putting it all together

Here's our finished JavaScript code, ready to be placed in the head element of the Web page. We've wrapped all the above code in a JavaScript function, updateClock():


<script type="text/javascript">
<!--

function updateClock ( )
{
  var currentTime = new Date ( );

  var currentHours = currentTime.getHours ( );
  var currentMinutes = currentTime.getMinutes ( );
  var currentSeconds = currentTime.getSeconds ( );

  // Pad the minutes and seconds with leading zeros, if required
  currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
  currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;

  // Choose either "AM" or "PM" as appropriate
  var timeOfDay = ( currentHours < 12 ) ? "AM" : "PM";

  // Convert the hours component to 12-hour format if needed
  currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours;

  // Convert an hours component of "0" to "12"
  currentHours = ( currentHours == 0 ) ? 12 : currentHours;

  // Compose the string for display
  var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;

  // Update the time display
  document.getElementById("clock").firstChild.nodeValue = currentTimeString;
}

// -->
</script>

To make the clock update every second, we need to use the Window.setInterval() method from within the page's body tag to call our updateClock() function once per second. (For more on setInterval, see our tutorial on setTimeout and setInterval.) We should also call updateClock() at the moment the page loads, so that the clock appears straightaway:


<body onload="updateClock(); setInterval('updateClock()', 1000 )">

That's it! You can see the clock in action on this demo page. We've also added some CSS to the clock container to make it prettier.

Feel free to use any of the above JavaScript code to make a clock for your own website. You might like to try putting the various time components in separate span containers, so that you can style them individually. You could also try converting the code to display a 24-hour clock instead. Have fun!

Follow Elated

Related articles

Responses to this article

4 responses (oldest first):

01-Jul-10 06:10
How would I make it so i could have it display it like this:

Mon, July, 1st, 2010 , 07:10 am?

Thanks,
Steve C
01-Jul-10 07:13
Never Mind i got it... Heres the code that i used:



<script type="text/javascript">
<!--

function updateClock ( )
{
var currentTime = new Date ( );

var currentDay = currentTime.getDay ( );

//Convert the day component to day abbreviation
currentDay = ( currentDay == 0 ) ? "Sun" : currentDay;
currentDay = ( currentDay == 1 ) ? "Mon" : currentDay;
currentDay = ( currentDay == 2 ) ? "Tue" : currentDay;
currentDay = ( currentDay == 3 ) ? "Wed" : currentDay;
currentDay = ( currentDay == 4 ) ? "Thu" : currentDay;
currentDay = ( currentDay == 5 ) ? "Fri" : currentDay;
currentDay = ( currentDay == 6 ) ? "Sat" : currentDay;

var currentMonth = currentTime.getMonth( );

//Convert the month component to text month
currentMonth = ( currentMonth == 0 ) ? "January" : currentMonth;
currentMonth = ( currentMonth == 1 ) ? "February" : currentMonth;
currentMonth = ( currentMonth == 2 ) ? "March" : currentMonth;
currentMonth = ( currentMonth == 3 ) ? "April" : currentMonth;
currentMonth = ( currentMonth == 4 ) ? "May" : currentMonth;
currentMonth = ( currentMonth == 5 ) ? "June" : currentMonth;
currentMonth = ( currentMonth == 6 ) ? "July" : currentMonth;
currentMonth = ( currentMonth == 7 ) ? "August" : currentMonth;
currentMonth = ( currentMonth == 8 ) ? "September" : currentMonth;
currentMonth = ( currentMonth == 9 ) ? "October" : currentMonth;
currentMonth = ( currentMonth == 10) ? "November" : currentMonth;
currentMonth = ( currentMonth == 11) ? "December" : currentMonth;

var currentDate = currentTime.getDate( );

// Add suffix to the date
currentDate = ( currentDate == 1 || currentDate == 21 || currentDate == 31 ) ? currentDate + "st" : currentDate;
currentDate = ( currentDate == 2 || currentDate == 22 ) ? currentDate + "nd" : currentDate;
currentDate = ( currentDate == 3 ) || currentDate == 23 ? currentDate + "rd" : currentDate;
currentDate = ( currentDate > 3 || currentDate < 21 || currentDate > 23 || currentDate < 31 ) ? currentDate + "th" : currentDate;


var currentHours = currentTime.getHours ( );
var currentMinutes = currentTime.getMinutes ( );

// Pad the minutes and seconds with leading zeros, if required
currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;

// Choose either "AM" or "PM" as appropriate
var timeOfDay = ( currentHours < 12 ) ? "AM" : "PM";

// Convert the hours component to 12-hour format if needed
currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours;

// Convert an hours component of "0" to "12"
currentHours = ( currentHours == 0 ) ? 12 : currentHours;

// Compose the string for display
var currentTimeString = "Today is : " + currentDay + " " + currentMonth + " " + currentDate + " " + currentHours + ":" + currentMinutes + " " + timeOfDay;

// Update the time display
document.getElementById("clock").firstChild.nodeValue = currentTimeString;
}

// -->
</script>
05-Jul-10 04:04
@arrow816: Looks good - thanks for posting your solution.

Cheers,
Matt
05-Jul-10 09:19
Yep, No Problem, always try and help out where I can.

Thanks for the great clock,
Steve C

Post a response

Want to add a comment, or ask a question about this article? Post a response.

To post responses you need to be a member. Not a member yet? Signing up is free, easy and only takes a minute or two. Sign up now.

Top of Page