我想以编程方式将 1-12 范围内的整数转换为相应的月份名称。 (例如 1 -> 一月、2 -> 二月)等在一个语句中使用 Java Calendar 类。
注意:我只想使用 Java Calendar 类来完成此操作。不建议任何 switch-case 或字符串数组解决方案。
谢谢。
Calendar
类不是最好使用的类。
以下是仅使用
int
类获取由 Calendar
值指定的所需月份(其中一月为 1)的月份名称的示例:
// Month as a number.
int month = 1;
// Sets the Calendar instance to the desired month.
// The "-1" takes into account that Calendar counts months
// beginning from 0.
Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, month - 1);
// This is to avoid the problem of having a day that is greater than the maximum of the
// month you set. c.getInstance() copies the whole current dateTime from system
// including day, if you execute this on the 30th of any month and set the Month to 1
// (February) getDisplayName will get you March as it automatically jumps to the next
// Month
c.set(Calendar.DAY_OF_MONTH, 1);
// Returns a String of the month name in the current locale.
c.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault());
上面的代码将返回系统语言环境中的月份名称。
Locale
替换为特定区域设置(例如 Locale.getDefault()
)来指定另一个 Locale.US
。
使用
DateFormatSymbols
自豪地从bluebones.net复制并粘贴:
import java.text.*;
String getMonthForInt(int m) {
String month = "invalid";
DateFormatSymbols dfs = new DateFormatSymbols();
String[] months = dfs.getMonths();
if (m >= 0 && m <= 11 ) {
month = months[m];
}
return month;
}
你读过 API 了吗? getDisplayName(...) 方法看起来是一个不错的起点。在一个声明中做到这一点是一项可怕的要求。
Month.of( 12 ).getDisplayName( TextStyle.FULL , Locale.US )
…或者…
Month.DECEMBER.getDisplayName( TextStyle.FULL , Locale.US )
十二月
java.time.Month
枚举。该类是 java.time 包的一部分,现在取代了麻烦的旧遗留日期时间类,例如 Date
和 Calendar
。
要本地化,请指定:
示例代码。
Month month = Month.of( 7 );
String outputConstantName = month.toString();
String outputMonthNameEnglish = month.getDisplayName( TextStyle.FULL , Locale.US );
String outputMonthQuébec = month.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH );
month.toString():七月
输出月份名称英语:July
输出月份魁北克:juillet
按名称而不是月份编号使用
Month
枚举对象可以方便、更易于阅读并且不易出错。
String output = Month.JULY.getDisplayName( TextStyle.FULL , Locale.US ) ;
java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如
java.util.Date
、Calendar
和SimpleDateFormat
。
Joda-Time 项目现在处于维护模式,建议迁移到 java.time 类。
要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310。
从哪里获取java.time类?
The ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是 java.time 未来可能添加的内容的试验场。您可能会在这里找到一些有用的类,例如
Interval
、YearWeek
、YearQuarter
和 more。