private static final ArrayList<HashMap<String, Object>> YEAR_LIST;
private static final List<HashMap<String, String>> MONTH_LIST;
private static String currentMonth;
static {
//start 这段代码用于向页面setAttribute年份以及月份
//获取当前年份及前2年
Calendar cal = Calendar.getInstance();
int currYear = cal.get(Calendar.YEAR);
// List<HashMap<String, Object>> yearList = new ArrayList<>();
YEAR_LIST = new ArrayList<>();
// for(int i = currYear-2; currYear >= i; i++){
for(int i = currYear; i > currYear-3; i--){
HashMap<String, Object> map = new HashMap<>();
map.put("year",i);
YEAR_LIST.add(map);
}
//获取当前月份
currentMonth = String.valueOf(cal.get(Calendar.MONTH)+1);
if (currentMonth.length() < 2)
currentMonth = "0" + currentMonth;
//获取12个月份
int currMonth = 0;
MONTH_LIST = new ArrayList<>();
HashMap<String, String> maps = null;
for (int y = currMonth+12; y > currMonth; y--) {
maps = new HashMap<>();
if (y < 10) {
maps.put("month", "0"+y);
} else {
maps.put("month", ""+y);
}
MONTH_LIST.add(maps);
}
//将12个月份中remove当前月份 其中list有个size为0的map
Collection<String> coll = maps.values();
while (coll.contains(currentMonth)) {
coll.remove(currentMonth);
}
//remove size为0的map
Iterator<HashMap<String, String>> iter = MONTH_LIST.iterator();
while (iter.hasNext()) {
HashMap<String, String> map = iter.next();
if (map.size()==0)
iter.remove();
}
//end
}
request.setAttribute("yearList", YEAR_LIST);
request.setAttribute("monthList", MONTH_LIST);
request.setAttribute("currentMonth", currentMonth);
效果如下: