Получение автономного названия месяца на удивление трудно выполнить «правильно» в Java. (По крайней мере, на момент написания статьи. Я сейчас использую Java 8).
Проблема в том, что в некоторых языках, включая русский и чешский, автономная версия названия месяца отличается от версии для форматирования. Кроме того, похоже, что ни один Java API не даст вам «лучшую» строку. Большинство ответов, опубликованных здесь, пока предлагают только версию форматирования. Ниже приведено рабочее решение для получения автономной версии названия одного месяца или получения массива со всеми из них.
Надеюсь, это спасет кого-то еще!
/**
* getStandaloneMonthName, This returns a standalone month name for the specified month, in the
* specified locale. In some languages, including Russian and Czech, the standalone version of
* the month name is different from the version of the month name you would use as part of a
* full date. (Different from the formatting version).
*
* This tries to get the standalone version first. If no mapping is found for a standalone
* version (Presumably because the supplied language has no standalone version), then this will
* return the formatting version of the month name.
*/
private static String getStandaloneMonthName(Month month, Locale locale, boolean capitalize) {
// Attempt to get the standalone version of the month name.
String monthName = month.getDisplayName(TextStyle.FULL_STANDALONE, locale);
String monthNumber = "" + month.getValue();
// If no mapping was found, then get the formatting version of the month name.
if (monthName.equals(monthNumber)) {
DateFormatSymbols dateSymbols = DateFormatSymbols.getInstance(locale);
monthName = dateSymbols.getMonths()[month.getValue()];
}
// If needed, capitalize the month name.
if ((capitalize) && (monthName != null) && (monthName.length() > 0)) {
monthName = monthName.substring(0, 1).toUpperCase(locale) + monthName.substring(1);
}
return monthName;
}
/**
* getStandaloneMonthNames, This returns an array with the standalone version of the full month
* names.
*/
private static String[] getStandaloneMonthNames(Locale locale, boolean capitalize) {
Month[] monthEnums = Month.values();
ArrayList<String> monthNamesArrayList = new ArrayList<>();
for (Month monthEnum : monthEnums) {
monthNamesArrayList.add(getStandaloneMonthName(monthEnum, locale, capitalize));
}
// Convert the arraylist to a string array, and return the array.
String[] monthNames = monthNamesArrayList.toArray(new String[]{});
return monthNames;
}