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;
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"> </span>
By placing the
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!
arrow816 says
How would I make it so i could have it display it like this:
Mon, July, 1st, 2010 , 07:10 am?
Thanks,
Steve C
arrow816 says
Never Mind i got it… Heres the code that i used:
NiS says
an idea for a futur article : an analog annual clock (one year cycle)
matt says
@arrow816: Looks good – thanks for posting your solution. π
Cheers,
Matt
arrow816 says
Yep, No Problem, always try and help out where I can.
Thanks for the great clock,
Steve C
Doobular says
Matt,
Thank you so much for this article, it really was exactly what I was looking for. For someone who has a tiny background in programming and none in java, the explanation was easy enough to understand how this script works, and did not just give me a reward with no lesson, so thanks.
Offhand, could you maybe suggest a source to start picking up java? I figure most guides would be good, but was just curious if you knew of a better-than-most starting point, or something along those lines. I have been occupied with other studies, and would like to start learning some more languages.
Thanks ahead,
Doob
matt says
Hi Doob,
I’m glad you found the article helpful.
Please note that Java and JavaScript are two different (although somewhat related) languages that do different things – don’t confuse the two!
Assuming you mean JavaScript, then you can’t go wrong with JavaScript: The Definitive Guide:
http://www.amazon.com/exec/obidos/ASIN/0596000480/
Cheers,
Matt
aLaMaT says
Thank you so much for this code!
May I ask what do I need to change to make the time be set? I need to set it to the Server time instead of the client time.
Please help.
chrishirst says
javascript runs on the client not the server and once the page is delivered to the client no more server communication occurs.
You can seed the clock by passing a date value to the page from the server and using that in place of the new Date
SU45 says
How do I alter this clock code to make the clock countdown to a specific date, such as Christmas for example?
matt says
@SU45: Create a new Date object for your target date and the current date. I think you could then use the UTC() method to convert both dates to UTC format in milliseconds, then subtract one from the other. Then divide the resulting value by the number of milliseconds in a day, hour, etc to get the countdown values, which you can then display in the page.
More on working with dates:
http://www.elated.com/articles/working-with-dates/
Cheers,
Matt
SU45 says
Almost done, I just need the Days, Hours, Mins, Secs all on new lines within the countdown box. How do I insert a line break for each? I am not overly familiar with coding because I usually use software to build web-pages, hopefully the solution is simple?
Here’s the code:
It’s OK, I’ve sorted it out now. I found the place where the breaks go.
[Edited by SU45 on 30-Mar-11 15:36]
SU45 says
Almost done now.
Just a couple of things I’d like to correct.
Regarding “seconds” when there is only “1 second” remaining, my code currently displays “seconds” instead the correct “second” for “1”; how do I change this?:
Also when the hours are at midnight (if days are remaining) it will display “0 hours” whereas when hours (and mins) are at zero I would prefer not to display the zero hours or mins, so that instead of “0 hours” (or “O minutes”) the field is completely nonexistent. How can I do this?
[Edited by SU45 on 31-Mar-11 01:17]
matt says
@SU45: Sounds like you’re doing great! π
You already have the code in there to display “minute” and “hour” when there’s only 1 minute or hour. So just copy that for the seconds too:
BTW you need “ ” not “ ”.
For your second question, again it looks like you already have that in your code. Basically you want something like:
SU45 says
Yes, in theory it should be an easy task to duplicate the code already used (regarding hours to hour and minutes to minute: for seconds to second) but whatever I try my additions cause the whole thing to vanish. I can’t seem to figure out what I am doing wrong. I’m probably making a silly mistake because I am a JavaScript novice, but I have no idea what the mistake is.
π
Likewise I cannot seem to ‘out’ the hours when the hours are zero and days are remaining. If there are no days remaining then the hours will be ‘out’ fine, but I’d also like to do this for zero hours when days are remaining.
Maybe I need to use something like this, but this doesn’t work:
I did however manage to add the semicolon for nbsp although it seems to work just the same with or without the semicolon, is the semi colon essential?
This is where I am at so far: http://singularity-2045.org/countdown.html
matt says
@SU45: Have you checked your browser’s error console for JavaScript errors?
I’ll take a closer look tomorrow if I have time…
Diggadee says
Hi Matt,
Nicely written post. Very helpful!
This is a question for Matt, or others…
Do you think that Matt’s code wold be a good starting point to accomplish this:
I’d like to create a clock or odometer style display that would allow me to freely set the variable that governs the rate of counting. The display then changes as fast as necessary to always display the year-to-date number at the rate I have specified. Sort of a population counter or a website hit counter, but with rates that I’d control.
I’d use it to display on my website the incidence of various illnesses each year. Based on the known rate of incidence of a particular illness each year (this is the variable that I would input–for example, “6,285 people in the specified population will contract XXX disease in 2011”), and the portion of the year that has passed until the present date and time, the display would show the year-to-date number of people who had contracted that disease– 4,286, or 792, or 177, or whatever.
Each time a user opens or refreshes the page, the display would update to the correct count relative to the current date and time. Or, if the code would allow it, the display would continuously update while the user remains on that page.
Suggestions?
matt says
@SU45: yes the semicolon is essential.
I’m struggling to understand exactly what you want to do with the days/hours thing. An example might help. Can you post an example in a new topic please, and we can take it from there?
http://www.elated.com/forums/authoring-and-programming/topic/new/
@Diggadee: If I understand you correctly, then you’d want to multiply your yearly figure by the proportion of the year that has so far elapsed (based on the current date retrieved from the Date() object), then display the figure in the page. You’d wrap this in a function, then call it periodically using setInterval():
http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
If you’d like further help on this, please start a new topic:
http://www.elated.com/forums/authoring-and-programming/topic/new/
geneteninty says
Thank you for this article, it help me. The way that you explain each steps helps. Thanks again
matt says
@geneteninty: Thanks for your comment. I’m glad you found the article helpful!
minegro says
Hi,
I realize this article is a bit old but, it’s the best one I’ve found for what I was trying to do. In the article you mentioned
“You might like to try putting the various time components in separate span containers, so that you can style them individually.”
I’m extremely new at this and have actually (surprisingly) gotten everything else to work except, I would love to be able to display the hours, minutes and seconds under separate div or span tags in order to modify them individually using css. Any help with this would be extremely helpful. Keep in mind I’m a complete noob and would love as step by step instructions as you possibly have patience for. I’ve pasted the code below.
I apologize in advance if it’s very long and dirty…
matt says
@minegro: I think all you’d need to do is create 3 spans:
<span id=”hours”> </span>
<span id=”minutes”> </span>
<span id=”seconds”> </span>
Then replace:
with:
Cheers,
Matt
minegro says
matt,
Thanks so much for the help. I actually figured it out. Without having to re-write all the code and clean everything up to make up for my novice discrepancies, The quickest and easiest thing was to create a separate update function for each component in the clock and displaying them that way. I think the problem is that I have all the date and weather functions combined on one thing and they’re not the most efficiently written as I was figuring it out as I went along. When I’ve learned a bit more I’ll be able to go back in and re-write all the code much cleaner.
Thanks again though, I really appreciate the response.
Warmest,
matt says
@minegro: Great, glad you got it working π
creaweb says
Good stuff!
I used it to create an analogic clock:
http://apps.mathieu-rodic.com/Beautiful/Clock
matt says
@creaweb: Cool, I like it π
Dissi says
Great job on clock and documentation! Thanks so much for the information.
I have one question, when I attempt to seed the time to start the clock, I am getting error on console .
currentTime.getHours is not a function
When I return the code to new date(), my clock appears, this tells me somehow the formatting of my variable time isn’t correct? Can you help me understand what format the data should be in? I am pulling time from our iseries.
thanks so much in advance, sorry for the noob question.
Dissi
matt says
@Dissi: This article lists the various date formats that you can pass to ‘new Date()’:
http://www.elated.com/articles/working-with-dates/
Hope that helps!
Matt
Dissi says
hm, I saw the article and I think I have followed the guidelines but I’m still getting errors. Although the error message is different now. I put an alert after I load currentTime and it tells me invalid date. The date I’m loading into the variable is formatted as follows: ‘2011,06,23,09,18,23’. I have tested by hardcoding in those values and still get invalid date.
I must need more coffee….
What I am trying to accomplish is to load a date with date and time values to start my clock. It sounded sooo easy.
thanks for all your help, sorry im still stuck.
Dis
matt says
@Dissi: Your date format works fine for me:
This displays the following alert:
Sat Jul 23 2011 09:18:23 GMT+1000 (EST)
Matt
Dissi says
ah well, once I realized i was not updating my current copy of the html. All was fine.
thanks for all your help!
Dis
matt says
@Dissi: Great, glad you got it working! π
roymj88 says
Great post.. Thanks for sharing this.. i was searching for something just like this one..
SU45 says
Here is the code I finally settled on, which I think is correct, it works for me:
[Edited by SU45 on 25-Feb-12 05:04]
matt says
@SU45: Glad you got it working how you wanted in the end π
Robert30 says
Hi good morning,
I like the script, but I was wondering how I can add a leading 0 (zero) for hours from 0:00 to 9:00 i.e. 07:35 a.m.
Thanks!
– Robert.
Edit: Never mind my question, I already figured it out when I came back with my coffee.. it’s a little early in the morning π
currentHours = ( currentHours == 0 ) ? 10 : “0” + currentHours;
^^ Is what I added.
Edit 2: Ok that didn’t work π
But I bet this does..
// Pad the hours, minutes and seconds with leading zeros, if required
currentMinutes = ( currentMinutes < 10 ? “0” : “” ) + currentMinutes;
currentSeconds = ( currentSeconds < 10 ? “0” : “” ) + currentSeconds;
currentHours = ( currentHours < 10 ? “0” : “” ) + currentHours;
Seems I wasn’t awake after all π
[Edited by Robert30 on 23-Aug-12 11:38]
bobbyhabib says
The way the javascript is written causes resources of the clock not to be free and stay alive in memory. After testing this code I noticed the memory of the browser session was being eaten up because the updateClock function you’ve assigned via setInterval calling the javascript function, keeps a live reference to everything that was in-scope of the function call during that function call (whether it uses it or not). This keeps all variables in the updateClock function alive in memory until it’s eaten all memory possible and not releasing the reference. You can release this by setting the setInterval and embedding the funtion in the same statement. It’s not a memory leak in the function, but the way it’s implemented that causes this problem.
The way around this is to do the following;
<script type=”text/javascript”>
setInterval(function updateClock() {
var monthNames = [“January”, “February”, “March”, “April”, “May”, “Jume”, “July”, “August”, “Spetember”, “October”, “November”, “December”];
var currentTime = new Date();
var currentDay = currentTime.getDate();
var currentMonth = monthNames[currentTime.getMonth()];
var currentYear = currentTime.getYear();
var currentHours = currentTime.getHours();
var currentMinutes = currentTime.getMinutes();
var currentSeconds = currentTime.getSeconds();
currentMinutes = (currentMinutes < 10 ? “0” : “”) + currentMinutes;
currentSeconds = (currentSeconds < 10 ? “0” : “”) + currentSeconds;
var timeOfDay = (currentHours < 12) ? “AM” : “PM”;
currentHours = (currentHours > 12) ? currentHours – 12 : currentHours;
currentHours = (currentHours == 0) ? 12 : currentHours;
var currentTimeString = currentMonth + ” ” + currentDay + “, ” + currentYear + ” ” + currentHours + “:” + currentMinutes + “:” + currentSeconds + ” ” + timeOfDay;
document.getElementById(“clock”).firstChild.nodeValue = currentTimeString;
delete currentTime;
}, 1000);
</script>
You could make this a anonymous function if you like.
Hope this helps somebody trying to achieve a active clock on your web page without killing memory on the client. π
[Edited by bobbyhabib on 24-Aug-13 09:31]
RabiaNazKhan says
Undoubtedly an awesome article! easy to understand, very informative and most importantly the code worked just as i wanted!
Thank you π
amansh29894 says
var d = new Date();
var date = d.getDate();
var month = d.getMonth();
var montharr =[“Jan”,”Feb”,”Mar”,”April”,”May”,”June”,”July”,”Aug”,”Sep”,”Oct”,”Nov”,”Dec”];
month=montharr[month];
var year = d.getFullYear();
var day = d.getDay();
var dayarr =[“Sun”,”Mon”,”Tues”,”Wed”,”Thurs”,”Fri”,”Sat”];
day=dayarr[day];
var hour =d.getHours();
var min = d.getMinutes();
var sec = d.getSeconds();
document.getElementById(“date”).innerHTML=day+” “+date+” “+month+” “+year;
document.getElementById(“time”).innerHTML=hour+”:”+min+”:”+sec;
if you have any problem then here is a complete tutorial on http://www.talkerscode.com with demo http://talkerscode.com/webtricks/digital-clock-with-complete-time-and-date-using-css-and-javascript.php
chrishirst says
If you guys who like spamming your ‘solutions’ could get up to date, it would be nice. That way you actually ADD something useful instead of just repeating ‘stuff’.
You do not need to have arrays holding weekday names and month names any more, which then needs converting for the visitor language. Instead you can use the .toLocaleDateString (Supported in Firefox, Chrome, IE 11+ Opera, Safari) which can output the information in the same language as the visitors browser is using.
Example:
This gets the browser language from “navigator.language” property then when you pass that to the .toLocaleDateString() method as a parameter it will return the weekday name or month name in the appropriate language for the end user
A Mozilla Developer Walkthrough:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
Phuong Vu Anh says
How can I make this as 00:00 as default, then let it count upward?
Arc says
Nice work thanks for the clear explaination
Matt Doyle says
You’re welcome π
Jean-Paul Sevestre says
Is there a javascript function calculating the local sun time please?
i.e. what solar time is it here, given latitude and longitude?
Dil*****k says
It is good practici to use switch statement instead of ?: operator
Matt Doyle says
Switch statements are for when you have several different values uni want to test for. Ternary (or if…then…else) is for testing a single value.
alex says
Hi, is it possible to write a clock that goes back in time?
Matt Doyle says
Do you mean like a countdown clock that counts down to a date in the future?