我正在尝试为用户获取时区。
为此,我有一个国家代码,它是一个有效的 ISO 国家代码。这些代码是 ISO-3166 定义的大写两字母代码。您可以在许多网站上找到这些代码的完整列表,例如: http://www.chemie.fu-berlin.de/diverse/doc/ISO_3166.html
我认为答案是“不,因为它是多对多的关系……像美国这样的国家/地区可以有多个时区……”。这就是问题...
我试过类似的东西:
//CountryEnum contains ISO_3166 values (http://www.chemie.fu-berlin.de/diverse/doc/ISO_3166.html)
//List all country to test timezone:
for (int i = 0; i < CountryEnum.values().length; i++) {
String isoCountryCode = CountryEnum.values()[i].name();// Get the iso country code
Locale locale = new Locale(isoCountryCode);// Build a country specific locale
Calendar calendar = Calendar.getInstance(locale);// Build a calendar with the specific locale
String timeZone = calendar.getTimeZone().getDisplayName();// Build a timeZone with the calendar
System.out.println("LOCALE : "+locale+" / COUNTRY: "+isoCountryCode+" / TIMEZONE: "+timeZone);
}
但它总是返回服务器时区......
有什么想法吗?
最佳答案
Locale
不是TimeZone
,反之亦然。检查Javadoc对于您正在使用的方法 - 第一行说
Gets a calendar using the default time zone and specified locale.
这就是您获得默认时区的原因 - 因为您在获取日历时没有指定时区。
想想 Jon 所说的 - 如果您知道在您确定用户来自美国的情况下您想要使用哪个时区,那么您可以调用 Calendar.getInstance
采用时区 和 语言环境的方法。另一方面,如果您不能明确地说出您要在这里做什么,那么请回到绘图板并多考虑一下您的要求,而不是查看您的实现。
如果您不能回答前面的问题,我认为大多数网站的标准追索权是允许用户指定他们的首选时区(如果他们在服务器上有永久帐户)并默认使用服务器的时区,如果他们没说别的。如果他们没有永久帐户,并且他们正在向您提供时间信息(例如 XML 上传),那么他们将必须指定他们在请求中使用的时区,或者(可能更好)您要求始终使用 UTC。
关于java - 有没有办法获得(仅)国家代码(有效的 ISO-3166 代码)的时区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1389837/