简体   繁体   中英

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 should 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM