Handling Timezone in webclient Timer


This post is the continuation of my previous post “Showing Timer in webclient”. – i could not handled timezone in my previous code. In detail if you are running a server in one timezone, say US(GMT-08:00)  and you are accessing the server webclient in different machine which has different timezone, say, India(GMT+05:30). So already written code is failed to show the correct server time.
First analyze, what was the problem in previous code:

var time = <%=System.currentTimeMillis()%>
var date = new Date(time);

In the above code, am getting server time in milliseconds and set the same in javascript Date object.
var date = new Date(time) – while executing this line, server will get browser timezone and set that timezone into this date object. Due to this we are getting incorrect server time.

Solution to this problem is by setting year, month, day, hours, minutes & seconds separately to Date class.  Here Date class does not take browser timezone.

<%
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int date = c.get(Calendar.DATE);
int hrs = c.get(Calendar.HOUR);
int mins = c.get(Calendar.MINUTE);
int secs = c.get(Calendar.SECOND);
%>
var date = new Date(<%=year%> , <%=month%> , <%=date%> , <%=hrs%> , <%=mins%> , <%=secs%> );

For better understanding, once again i put the entire code here with the updated one.

Sample code with Timezone handling.

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

<%
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int date = c.get(Calendar.DATE);
int hrs = c.get(Calendar.HOUR);
int mins = c.get(Calendar.MINUTE);
int secs = c.get(Calendar.SECOND);
%>

<script>

var months = new Array(”Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”, “Aug”, “Sep”, “Oct”, “Nov”, “Dec”);
function showCurrentTime(){
var date = new Date(<%=year%> , <%=month%> , <%=date%> , <%=hrs%> , <%=mins%> , <%=secs%> );
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);
</script>

Advertisements

Tags: , , , , , , , ,

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s


%d bloggers like this: