ServeltRequest有一个getLocale()方法,定义为:
Returns the preferred Locale that the client will accept content in, based on the Accept-Language header.
我编写了以下简单的程序:
Locale loc = new Locale("ja", "JP", "JP");
Calendar calendar = Calendar.getInstance(loc);
System.out.println(calendar.get(calendar.YEAR));
它成功显示了日本皇历而不是公历。
现在,我的问题是:用户如何设置他的浏览器,例如Chrome 以便 request.getLocale()
将返回 Locale("ja", "JP", "JP")
?我尝试添加日语,但仍然得到了 GregorianCalendar。
最佳答案
来自 private static Calendar createCalendar(TimeZone zone, Locale aLocale)
的源代码(当您调用 getCalendar(locale)
时在内部调用的方法:
if (aLocale.hasExtensions()) {
String caltype = aLocale.getUnicodeLocaleType("ca");
if (caltype != null) {
switch (caltype) {
...
case "japanese":
cal = new JapaneseImperialCalendar(zone, aLocale);
break;
...
}
}
}
if (cal == null) {
...
if (aLocale.getVariant() == "JP" && aLocale.getLanguage() == "ja"
&& aLocale.getCountry() == "JP") {
cal = new JapaneseImperialCalendar(zone, aLocale);
} else {
cal = new GregorianCalendar(zone, aLocale);
}
}
正如您在第二部分中所看到的,区域设置需要包含“country = JP”、“language = ja”和“variant = JP”,即区域设置字符串 ja_JP_JP
。
问题是浏览器似乎不直接支持在语言设置中设置国家/地区和变体,因此您可能必须自己推断 - 根据您的需要:
- 如果语言为
ja
,则假定国家/地区和变体均为JP
- 使用某种形式的地理位置来获取浏览器位置,如果浏览器位于日本,则将国家/地区和变体设置为
JP
- 让用户选择,即从语言开始,然后让用户选择他们想要使用的日历类型
关于java - 日本皇历和地区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32604108/