Java 獲取當前時間往前推最近12月“年-月”格式的時間,方便統計使用

**java 獲取當前時間往前推最近12月“年-月”格式的時間,方便統計使用
import java.util.Arrays;
import java.util.Calendar;
/**
* 輸出如下:
* “[2016-02, 2016-03, 2016-04, 2016-05, 2016-06, 2016-07,
* 2016-08, 2016-09, 2016-10, 2016-11, 2016-12, 2017-01]”
*/
public static void main(String[] args) {
getLatest12Month();
}

/**
* 獲取當前系統時間最近12月的年月(含當月)
*/
public static void getLatest12Month(){
String[] latest12Months = new String[12];
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)+1); //要先+1,才能把本月的算進去
for(int i=0; i<12; i++){
cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)-1); //逐次往前推1個月
latest12Months[11-i] = cal.get(Calendar.YEAR)+ “-” +fillZero(cal.get(Calendar.MONTH)+1);
}
System.out.println(Arrays.toString(latest12Months));
}
/**
* 格式化月份
*/
public static String fillZero(int i){
String month = “”;
if(i<10){
month = “0” + i;
}else{
month = String.valueOf(i);
}
return month;
}**

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章