java locale utc,如何从Locale获取当前时间和时区?

I have this weird problem, when I create a calendar with a locale, the TimeZone just reverts to the local one

public void start(Locale locale){

String s = locale.getDisplayName();

System.err.println(s);

Calendar c = new GregorianCalendar(locale);

System.err.println(c.getTimeZone());

}

And this is the output:

español (Argentina)

sun.util.calendar.ZoneInfo[id="Europe/Bucharest", //etc more useless date here....

How can i get the proper time from a specific locale ?

解决方案

The short answer: you can't.

The long answer: There is no such thing as "proper time zone for a locale". That's just because there are a few countries that have more than one time zone (for example United States). Time zone is a different concept.

Anyway, you are looking to solve your problem. I am guessing that you are writing a web application and you see that the time zone is reverting to the server default. That's a typical situation. Both Locale.getDefault() and TimeZone.getDefault() will return server-related information. The JVM has no way of knowing the "proper" time zone. So what can you do about it?

You can add time zone information to user profile (if you have one), or create a time zone combo box (so that the user can switch at runtime). Then you can assign an appropriate object to DateFormat instance and it will convert time zone automatically.

You can read the current time zone offset from the client via JavaScript Date Object's getTimezoneOffset() function and somehow (AJAX) send it to the server. The problem with this method is that there are several time zones with that offset, and the selected time zone might be inappropriate for other dates. Of course you can guess the time zone by polling the data around time change date, but this is probably not what you want to do.

You can send the unformatted time to the client (for example written as ISO 8601 date-time format or as a Unix time of the epoch in relation to UTC) and have Globalize or Dojo format date and time for you.

Out of these three possible choices, I always opt for number 1. By putting time zone information to user profile, you know for sure what his/her preferred time zone is, regardless of their current web browser, etc. Please keep in mind that some users might want to use your application while visiting other countries...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值