【发布时间】:2011-03-30 03:42:13
【问题描述】:
是否可以在不将DateFormat.get*Instance() 返回的对象转换为SimpleDateFormat 的情况下检索给定语言环境的默认模式?
我明白,在大多数情况下一切都会好起来的,但在javadoc、here 中有一条注释:“如果您想要更多地控制格式或解析,(或者想要给您的用户更多控制),您可以尝试将您从工厂方法获得的DateFormat 转换为SimpleDateFormat。这适用于大多数国家/地区;请记住将其放在try 块中以防万一一个不寻常的。”
所以我想知道,万一我“遇到不寻常的人”该怎么办?
代码示例:
/**
* Returns '\n'-separated string with available patterns.
* Optional adds appropriate language code to each pattern string.
*
* @param showLanguage Defines if language info is required.
* @return String with available patterns, optional (if showLanguage is set
* to "true") adds appropriate language code to each pattern.
*/
public String getPatternsForAvailableLocales(Boolean... showLanguage) {
/* Array of available locales */
Locale[] locales = DateFormat.getAvailableLocales();
String result = "";
for (Locale locale : locales) {
/* Add language info, if necessary */
if ((showLanguage.length > 0) && (showLanguage[0])) {
result += locale.getLanguage() + '\t';
}
/* Retrieving pattern */
try {
result += ((SimpleDateFormat)
DateFormat.getDateTimeInstance(DateFormat.SHORT,
DateFormat.SHORT, locale)).toPattern();
} catch (ClassCastException e) {
// ******************************** //
// What's up? Is there another way? //
// ******************************** //
}
result += '\n';
}
return result;
}
【问题讨论】:
-
如果您“遇到不寻常的人”,我不确定您是否可以做任何事情,因为它可能不是基于模式的。特别是因为开发人员可以通过
java.text.spi.DateFormatProvider提供自己的DateFormat。
标签: java locale simpledateformat