Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring application showing server time instead of 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 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?

like image 951
user1007895 Avatar asked Nov 30 '12 22:11

user1007895


3 Answers

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.

like image 106
kosa Avatar answered Nov 16 '22 15:11

kosa


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.

like image 43
Tomasz Nurkiewicz Avatar answered Nov 16 '22 17:11

Tomasz Nurkiewicz


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.

like image 2
Solubris Avatar answered Nov 16 '22 17:11

Solubris