Showing Timer in webclient

With javascript you can get the current time of client computer’s and showing them dynamically in browser which looks like a digital timer. Though we can able to show the client’s computer time but mostly that’s not needed for web developer’s. The main thing they required is to show the server time in client browser. Lets see how to do it.
A simple steps to achieve this,

  • Get the server time using java method currentTimeMillis() this should return current time(in milliseconds) of machine where the server is running.
  • Using javascript Date class you can parse that value in your required format and show in webclient.
  • Then increment the time with value 1000 for each seconds. This will simulate like the time is running each and every second.
  • Finally, do the above 2 steps every seconds.

Sample code.

<div id=”showTimer“></div> <!– Used to show the Digital Timer –>

var months = new Array(“Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”, “Aug”, “Sep”, “Oct”, “Nov”, “Dec”);
var time = <%=System.currentTimeMillis()%>
function showCurrentTime(){
var date = new Date(time);
var showdate = date.getDate() + ” ” + months[date.getMonth()] + ” ” +date.getFullYear() + “, ” ;
var hrs = date.getHours();
var mins = date.getMinutes();
var secs = date.getSeconds();
hrs = (hrs > 9) ? hrs : “0”+hrs;
mins = (mins > 9) ? mins : “0”+mins;
secs = (secs > 9) ? secs : “0”+secs;
var showtime =  hrs + ” : ” + mins + ” : ” + secs;
time = time+1000;
document.getElementById(“showTimer“).innerHTML=showdate + showtime;
setInterval(“showCurrentTime()”, 1000);


Tags: , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: