I need to convert my server time to the user's time depending on their time zone.
Is this the best way to figure out their timezone - by using the HttpServletRequest object?
Locale clientLocale = request.getLocale();
Calendar calendar = Calendar.getInstance(clientLocale);
TimeZone clientTimeZone = calendar.getTimeZone();
Unfortunately you cannot get the user's timezone from their request, as the client does not send the data. The locale in the request object is based on the user's Accept-Language header. What is the right timezone for "English"?
Two other possible approaches:
There's no real good simple solution to this though -- which is why most sites will ask for the user's timezone, or display dates in a relative format (e.g. 5 hours ago).
You can't get it from the
HttpServletRequest
. The information is not there.In JavaScript, however, you can get the timezone offset as follows:
You can use it to send back to server as (ajax) parameter or to apply changes on the rendered HTML. I would however not strictly rely on this. It should at least be configureable by the enduser itself.
Provide an dropdown box to your customer where he can enter his correct time zone. And use the one you determined from the locale by default.
Anyway: The W3C has this questions in its W3C Web Internationalization FAQs: Is it a good idea to use the HTTP Accept-Language header to determine the locale of the user?