我需要打印当月的过去6个月的名字.
例如,在2016年4月运行时,我需要打印:nov(2015),dec(2015),jan(2016),feb(2016),march(2016),4月(2016)
Format formatter = new SimpleDateFormat("MMMM YYYY");
Calendar c = Calendar.getInstance();
String[] thisAndLastFiveMonths = new String[6];
for (int i = 0; i < thisAndLastFiveMonths.length; i++) {
thisAndLastFiveMonths[i] = formatter.format(c.getTime());
c.add(Calendar.MONTH, -1);
System.out.println(c);
Run Code Online (Sandbox Code Playgroud)
使用Java Time API,您可以构造一个YearMonth表示当前年月的对象,并调用minusMonths减去若干个月.
然后,您可以获得月份名称的文本表示Month.getDisplayName(style, locale).给定TextStyle用于设置输出样式; 你可以SHORT用于你的情况:
短文本,通常是缩写.例如,星期一星期一可能输出"星期一".
public static void main(String[] args) {
for (int i = 5; i >= 0; i--) {
YearMonth date = YearMonth.now().minusMonths(i);
String monthName = date.getMonth().getDisplayName(TextStyle.SHORT, Locale.ENGLISH);
System.out.println(monthName + "(" + date.getYear() + ")");
}
}
Run Code Online (Sandbox Code Playgroud)
打印,在2016年4月投放时:
Nov(2015)
Dec(2015)
Jan(2016)
Feb(2016)
Mar(2016)
Apr(2016)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
273 次 |
| 最近记录: |