Thursday, September 4, 2008

JavaScript handling of time zones

On the project I am currently working on, we had a problem to solve regarding time zones with our application. From the web interface the user was entering time for some of the fields. The time was being sent to the server and stored in a database. The problem we ran into was the client time zone was different than the server timezone. The database on the server was converting all times that were saved to the server time zone. When the data was retrieved, it was displaying the server time values and presenting it to the user as if it were client local time. Obviously we were not taking time zones into account.

Like most problems, there is usually more than one way to solve it. The way we solved it, was to make sure that all of the times that were being passed back and forth through the REST web service calls were in GMT (Zulu) time. The database can convert to local time, but before it is sent to the client, it is converted back to GMT. Likewise, in the browser, the user can enter time in local time, but before it is sent to the server it is converted to GMT time.

The rub came in finding the right java script date functions to allow for conversion to and from GMT. The GMT string representations that were being passed back and forth, needed converted to the clients local time. This was easily accomplished by using the java script Date constructor.

var localTimeZoneDate = new Date(gmtTimeZoneDateStr);

The date components the UI implemented, needed to be initialized with milliseconds from epoch time. To get that information we simply called Date.parse(localTimeZoneDate);

On the server it was equally easy to convert the value retrieved from the database to GMT.
String dateFormatStr = "EEE, dd MMM yyyy HH:mm:ss z";
SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatStr );
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = dateFormat.parse(timeStr);

In reviewing what we did, there may have been an easier solution. Both the Java Date object and the JavaScript Date object, are able to return milliseconds from epoch. It would have been much simpler to just send that value back and forth, and not worry about the string format.

No comments: