Java从整数获取月份string

有没有更好的方法来压缩这种方法,即通过避免切换情况来减less圈复杂度?

String monthString; switch (month) { case 1: monthString = "January"; break; case 2: monthString = "February"; break; case 3: monthString = "March"; break; case 4: monthString = "April"; break; case 5: monthString = "May"; break; case 6: monthString = "June"; break; case 7: monthString = "July"; break; case 8: monthString = "August"; break; case 9: monthString = "September"; break; case 10: monthString = "October"; break; case 11: monthString = "November"; break; case 12: monthString = "December"; break; default: monthString = "Invalid month"; break; } System.out.println(monthString); 

尝试:

 import java.text.DateFormatSymbols; monthString = new DateFormatSymbols().getMonths()[month-1]; 

或者,您可以使用SimpleDateFormat:

 import java.text.SimpleDateFormat; System.out.println(new SimpleDateFormat("MMMM").format(date)); 

(你必须在Date对象中放置一个与你的月份相同的Date以使用第二个选项)。

取一个包含月份名称的数组。

 String[] str = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; 

那么你想在哪里采取月份使用如下:

 if(i<str.length) monthString = str[i-1]; else monthString = "Invalid month"; 

Month枚举

你可以使用Month枚举。 这个枚举被定义为Java 8及更高版本中内置的新java.time框架的一部分。

 int monthNumber = 10; Month.of(monthNumber).name(); 

输出将是:

十月

本土化

通过在相同的Enum上调用getDisplayName来本地化为英语以外的语言。

 String output = Month.OCTOBER.getDisplayName ( TextStyle.FULL , Locale.CANADA_FRENCH ); 

输出:

OCTOBRE

你可以有一个strigs数组并通过索引访问。

  String months[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; 
 import java.time.Month; Month exemple = new Month.of(12); //---return a Month object with value of December--- String month = exemple.toString(); //---if you want to convert Month to String---