[英]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.