开发者

How to get current date based on time zone or locale, or user preference?

开发者 https://www.devze.com 2023-01-05 17:22 出处:网络
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 zon

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号