Is there another way to get a user's time zone

2020-02-25 08:32发布

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();

3条回答
欢心
2楼-- · 2020-02-25 08:57

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

查看更多
smile是对你的礼貌
3楼-- · 2020-02-25 09:06

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.

查看更多
叛逆
4楼-- · 2020-02-25 09:13

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?

查看更多
登录 后发表回答