Java獲取近兩年和近六個月(存在bug)
阿新 • • 發佈:2019-02-19
private List<String> getNearDate(String isYear){ List<String> resultList = new ArrayList<String>(); Calendar cal = Calendar.getInstance(); if("0".equals(isYear)){ //近六個月 cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)+1); //要先+1,才能把本月的算進去 for(int i=0; i<6; i++){ cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)-1); //逐次往前推1個月 resultList.add(String.valueOf(cal.get(Calendar.YEAR)) + (cal.get(Calendar.MONTH)+1 < 10 ? "0" + (cal.get(Calendar.MONTH)+1) : (cal.get(Calendar.MONTH)+1))); } }else { //近兩年 int nowYear = cal.get(Calendar.YEAR); int lastYear = nowYear - 1 ; resultList.add(String.valueOf(nowYear)); resultList.add(String.valueOf(lastYear)); } return resultList; }
試試大月的31日和1月的最後幾天,會出錯的。
例如在3月31日執行:
cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)+1); //要先+1,才能把本月的算進去
時,會使得加1後變成4月31日,進而轉化到了五月份。
3月31日執行獲取近六個月時,會獲取到四月份。
笨辦法:
/** * 獲取近兩年或者近六個月日期 * @param isYear * @return */ private List<String> getDate(String isYear){ List<String> resultList = new ArrayList<String>(); Calendar cal = Calendar.getInstance(); if("0".equals(isYear)){ int MONTH_SIZE = 6 ; //獲取當前月 int month = cal.get(Calendar.MONTH)+1; int year = cal.get(Calendar.YEAR); String aResult = ""; if(month < 10){ aResult = year + "0" + month; }else{ aResult = "" + year + month; } resultList.add(aResult); //獲取之前五個月 for(int i = 0; i<MONTH_SIZE - 1; i++){ month = month - 1; if(0 == month){ month = 12; year = year - 1; } if(month < 10){ aResult = year + "0" + month; }else{ aResult = "" + year + month; } resultList.add(aResult); } }else { //年度取近兩年 int nowYear = cal.get(Calendar.YEAR); int lastYear = nowYear - 1 ; resultList.add(String.valueOf(nowYear)); resultList.add(String.valueOf(lastYear)); } return resultList; }