Is it possible to retrieve a default pattern for a given locale, without casting an object returned by DateFormat.get*Instance()
to a SimpleDateFormat
?
I understand, that in most cases everything will be OK, but there is a note in javadoc
, here: "If you want even more control over the format or parsing, (or want to give your users more control), you can try casting the DateFormat
you get from the factory methods to a SimpleDateFormat
. This will work for the majority of countries; just remember to put it in a try
block in case you encounter an unusual one."
So I wonder, what should I do in case I "encounter an unusual one"?
Related theme.
Code sample:
/**
* 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;
}