java 给定一个日期期间 返回形如Mar 2015 3/20-3/31的数据
最近一个项目中有个前台对于表头要求:
给定一个日期期间返回形如
Mar 2015 3/20-3/31
Apr 2015 4/1-4/30
这样的月年数据,简单的写了下代码,暂时没想到更好的办法
例如传进来的参数是 "2015-03-20"-"2016-04-08" 这样的形式
分三段处理:
第一段:起始日期的起始日期的月底
第二段:开始和结束月之间的所有月数据
第三段:结束日期的月初到结束日期
1 public List<String> loadMonthStr(String startDate, String endDate) throws Exception { 2 List<String> periodList = new ArrayList<>(); 3 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 4 GregorianCalendar cdStart = new GregorianCalendar(); 5 GregorianCalendar cdEnd = new GregorianCalendar(); 6 cdStart.setTime(sdf.parse(startDate)); 7 cdEnd.setTime(sdf.parse(endDate)); 8 9 sdf = new SimpleDateFormat("MMM yyyy", Locale.US); 10 int firstStart = cdStart.get(Calendar.DAY_OF_MONTH); 11 12 int lastEnd = cdEnd.get(Calendar.DAY_OF_MONTH); 13 int monthOfYear = cdStart.get(Calendar.MONTH) + 1; 14 15 boolean sameYearMonth = false; 16 String dateStr; 17 if (cdStart.get(Calendar.MONTH) == cdEnd.get(Calendar.MONTH) && cdStart.get(Calendar.YEAR) == cdEnd.get(Calendar.YEAR)) { 18 sameYearMonth = true; 19 } 20 21 if (sameYearMonth) { 22 dateStr = sdf.format(cdStart.getTime()) + " " + monthOfYear + "/" + firstStart + "-" + monthOfYear + "/" + lastEnd; 23 periodList.add(dateStr); 24 } else { 25 dateStr = sdf.format(cdStart.getTime()) + " " + monthOfYear + "/" + cdStart.get(Calendar.DAY_OF_MONTH) + "-" 26 + monthOfYear + "/" + cdStart.getMaximum(Calendar.DAY_OF_MONTH); 27 periodList.add(dateStr); 28 cdStart.set(Calendar.DAY_OF_MONTH, 1); 29 cdEnd.set(Calendar.DAY_OF_MONTH, 1); 30 cdStart.add(Calendar.MONTH, 1); 31 int startDay = 0; 32 int endDay = 0; 33 while (cdStart.compareTo(cdEnd) < 0) { 34 monthOfYear = cdStart.get(Calendar.MONTH) + 1; 35 startDay = 1; 36 endDay = cdStart.getActualMaximum(Calendar.DAY_OF_MONTH); 37 dateStr = sdf.format(cdStart.getTime()) + " " + monthOfYear + "/" + startDay + "-" + monthOfYear + "/" + endDay; 38 cdStart.add(Calendar.MONTH, 1); 39 periodList.add(dateStr); 40 } 41 dateStr = sdf.format(cdEnd.getTime()) + " " + (cdEnd.get(Calendar.MONTH) + 1) + "/" + 1 + "-" 42 + (cdEnd.get(Calendar.MONTH) + 1) + "/" + lastEnd; 43 periodList.add(dateStr); 44 } 45 return periodList; 46 }