Here is my code:
@RequestMapping(value="/test", method=RequestMethod.GET)
public @ResponseBody String test(HttpServletRequest request) {
Calendar calendar = new GregorianCalendar(request.getLocale());
String currentTime = calendar.getTime().toString();
return"Current Time: " + currentTime;
}
This is showing me this time:
Current Time: Fri Nov 30 22:45:42 UTC 2012
I am in the central time zone, so it should be showing me this:
Current Time: Fri Nov 30 14:45:42 CST 2012
Why am I getting the server time instead of the client time?
Your code executes on server irrespective where your client is. On server you will setup timezone for that machine, which will be used to calculate time. when you call calendar.getTime()
this timezone will be used.
If you want client time zone, you need to send it and use something SimpleDateFormat to convert server time to client timezone.
This piece of code is correct:
Calendar calendar = new GregorianCalendar(request.getLocale());
It basically creates an instance of Calendar
in a:
preferred Locale that the client will accept content in, based on the Accept-Language header
Your mistake is in converting Calendar
to Date
here:
calendar.getTime()
java.util.Date
class is time-zone agnostic and always its default toString()
implementation always uses system (your servers) time zone. If you want to format current server time in clients' time zone use the following code snippet:
DateFormat df = DateFormat.getDateTimeInstance(
DateFormat.LONG,
DateFormat.LONG,
request.getLocale()
);
df.format(new Date());
One final note: this display time on server using clients time zone. It's not clients time as set in browser (operating system). In order to figure out what is the time zone on the client you need to sent client's current time explicitly in HTTP request.
I recommend leaving the controller code to return UTC time. Then do the conversion to client time in either view layer or (better still) the javascript code that executes on the clients browser.
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