我想以编程方式将1-12范围内的整数转换为相应的月份名称.(例如1 - > 1月,2 - > 2月)等在一个语句中使用Java Calendar类.
注意:我想仅使用Java Calendar类来完成它.不建议任何开关盒或字符串阵列解决方案.
谢谢.
该Calendar班是不是当谈到在一个声明中获得本地化月份名称使用的最佳类.
以下是int仅使用Calendar类获取由值(1月为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());
Run Code Online (Sandbox Code Playgroud)
上面的代码将返回系统区域设置中的月份名称.
如果需要另一个语言环境,可以Locale通过替换Locale.getDefault()特定语言环境来指定另一个语言环境,例如Locale.US.
| 归档时间: |
|
| 查看次数: |
4635 次 |
| 最近记录: |