Is there another way to get a user's time zone from a HttpServletRequest object in Spring MVC? [duplicate]

橙三吉。 提交于 2020-01-10 10:29:23

问题


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

回答1:


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




回答2:


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.




回答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?



来源:https://stackoverflow.com/questions/6091804/is-there-another-way-to-get-a-users-time-zone-from-a-httpservletrequest-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!