[英]Print past 6 month names from current month in Java
我需要打印当前月份的过去6个月的名称。
例如,在2016年4月运行时,我需要打印:nov(2015),dec(2015),jan(2016),feb(2016),三月(2016),四月(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);
使用Java Time API ,您可以构造一个YearMonth
对象来表示当前的年月,并调用minusMonths
减去月数。
然后,您可以使用Month.getDisplayName(style, locale)
获得月份名称的文本表示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() + ")");
}
}
打印,于2016年4月运行:
Nov(2015)
Dec(2015)
Jan(2016)
Feb(2016)
Mar(2016)
Apr(2016)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.