13

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();
Roger
  • 131
  • 1
  • 1
  • 3

3 Answers3

17

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:

  • Use GeoIP on the client's IP to have a stab at their location, and look up (from tz) a close timezone
  • Use client-side Javascript to calculate their offset from UTC (subtract UTC from localtime), then look up timezones that match that offset (this will not be very granular as many timezones are e.g. +11 hours. You might be able to combine with the above).

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).

Jonathan Hedley
  • 10,442
  • 3
  • 36
  • 47
12

You can't get it from the HttpServletRequest. The information is not there.

In JavaScript, however, you can get the timezone offset as follows:

var offset = new Date().getTimezoneOffset();
// ...

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.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
3

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?

Ralph
  • 118,862
  • 56
  • 287
  • 383
  • 2
    **Timezones and languages are independent.** Russia has 9 timezones, which one should be used for `ru_RU`?. People living in Japan with their locale is set to `en_US` expects to see webpages in American English and time in JST – user454322 Sep 16 '14 at 04:12
  • @user454322: right that is the reason why it is only the default value and the user can change them. On the other hand, it will work correct for many locales. – Ralph Sep 16 '14 at 19:19