如何在Java中将整数转换为本地化的月份名称?tl;博士java.time

2022-08-31 09:44:48

我得到一个整数,我需要在各种区域设置中转换为月份名称:

区域设置 en-us 的示例:
1 -> 1 月 2 日
- 2 月 > 日

区域设置 es-mx 的示例:
1 -> Enero
2 -> Febrero


答案 1
import java.text.DateFormatSymbols;
public String getMonth(int month) {
    return new DateFormatSymbols().getMonths()[month-1];
}

答案 2

tl;博士

Month                             // Enum class, predefining and naming a dozen objects, one for each month of the year. 
.of( 12 )                         // Retrieving one of the enum objects by number, 1-12. 
.getDisplayName(
    TextStyle.FULL_STANDALONE , 
    Locale.CANADA_FRENCH          // Locale determines the human language and cultural norms used in localizing. 
)

java.time

从Java 1.8(或ThreeTen-Backport的1.7和1.6)开始,您可以使用以下命令:

Month.of(integerMonth).getDisplayName(TextStyle.FULL_STANDALONE, locale);

请注意,这是基于 1 的,即 1 表示 1 月。1 月至 12 月的范围始终为 1 到 12(即仅公历)。integerMonth