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();
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); ... }
HTTP dates are always expressed in GMT, never in local time.
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.
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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With