Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
like image 674
Roger Avatar asked May 23 '11 00:05

Roger


People also ask

How do I get client timezone in spring boot?

If you really want to do it yourself use the RequestContextUtils. getTimeZone(request) method. @RequestMapping public String foo(HttpServletRequest request) { TimeZone timezone = RequestContextUtils. getTimeZone(request); ... }

Does HTTP request contain timezone?

HTTP dates are always expressed in GMT, never in local time.

How do I find client time zone on my server?

there are 2 ways we get browser's timezone from request object. return of above can be easily converted into Timezone using below code: StringBuffer buffer = new StringBuffer(""); int absOffset = Math. abs(offset); int hrs = absOffset/60; int mins = absOffset%60; buffer.

How do you handle time zones in an application?

Always assume that timezone. Should the device switch timezones, add a dropdown to select which timezone the event is in, defaulting to the device's own timezone. Add an option to show/hide this timezone dropdown manually. Always store timestamps in UTC.


2 Answers

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

like image 86
Jonathan Hedley Avatar answered Sep 20 '22 08:09

Jonathan Hedley


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.

like image 20
BalusC Avatar answered Sep 19 '22 08:09

BalusC