How to get current date based on time zone or locale, or user preference?
If my web application is deployed in the US I will get US time regardless of the client's country. But if the client is in India, he sh开发者_Python百科ould get Indian time, either using the time zone or locale or user preference. What should I do?
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("US/Mountain"), Locale.US);
System.out.println(calendar.getTime());
Output: Fri Jul 02 12:15:35 IST 2010 Here I am getting IST time. But I need US/mountain time.
You're printing calendar.getTime()
which returns a java.util.Date
- and Date.toString()
uses the default time zone. (A java.util.Date
doesn't have an associated time zone or locale.)
Use a java.text.DateFormat
with the appropriate locale etc if you want to control formatting.
Alternatively, use Joda Time which is a much more competent date and time API to start with.
I think your question is how to get the local time for the client rather than formatting the server time using the clients date format.
In which case, you should use the locale of the client rather than hard coding it when creating the calendar - this will convert absolute time (milliseconds since Jan 1 1970) to the appropriate time zone.
You can use the ServletRequest.getLocale() to determine the clients preferred locale,
hope this helps.
精彩评论