Spring application showing server time, not client time

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 shows me this time:

 Current Time: Fri Nov 30 22:45:42 UTC 2012 

I am in the central time zone, so it should show me this:

 Current Time: Fri Nov 30 14:45:42 CST 2012 

Why am I getting server time instead of client time?

+4
source share
3 answers

Your code runs on the server no matter where your client is located. On the server, you set the time zone for this machine, which will be used to calculate the time. when you call calendar.getTime() , this timezone will be used.

If you want the client’s time zone, you need to send it and use SimpleDateFormat to convert the server time to the client’s time zone.

+4
source

This part of the code is correct:

 Calendar calendar = new GregorianCalendar(request.getLocale()); 

Basically a Calendar instance is created in the file :

prefers Locale to let the client accept content based on the Accept-Language header

Your error is converting Calendar to Date here:

 calendar.getTime() 

java.util.Date class is a time zone agnostic, and always its default implementation of toString() always uses the time zone of the system (your servers). If you want to format the current server time in the clients time zone, use the following code fragment:

 DateFormat df = DateFormat.getDateTimeInstance( DateFormat.LONG, DateFormat.LONG, request.getLocale() ); df.format(new Date()); 

One final note: this is the time it displays on the server using the client’s time zone. This is not the clients time set in the browser (operating system). To find out what is the time zone on the client, you need to explicitly send the current time of the client to the HTTP request.

+3
source

I recommend leaving the controller code to return UTC time. Then do the conversion to client time at the presentation level or (better) javascript code that runs in the client browser.

+1
source

All Articles