傳入時間按月分組
public static void main(String[] args) { String beg_date = "2017-01-01"; String end_date = "2018-02-02"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date begin = new Date(); Date end = new Date(); try { begin = sdf.parse(beg_date); end = sdf.parse(end_date); } catch (ParseException e) { System.out.println("日期輸入格式不對"); return; } String list = getDateInterval(begin, end); List<String> lis = Arrays.asList(list.split("\r\n")); for(String string:lis){ System.out.println(string); } // System.out.println(getDateInterval(begin, end)); }
private static String getDateInterval(Date begin, Date end) { // 開始日期不能大於結束日期 if (!begin.before(end)) { return null; } Calendar cal_begin = Calendar.getInstance(); cal_begin.setTime(begin); Calendar cal_end = Calendar.getInstance(); cal_end.setTime(end); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); StringBuffer strbuf = new StringBuffer(); while (true) { if (cal_begin.get(Calendar.YEAR) == cal_end.get(Calendar.YEAR) && cal_begin.get(Calendar.MONTH) == cal_end .get(Calendar.MONTH)) { strbuf.append(sdf.format(cal_begin.getTime())).append("\r\n"); // .append("~") // .append(sdf.format(cal_end.getTime())).append("\r\n"); break; } String str_begin = sdf.format(cal_begin.getTime()); String str_end = getMonthEnd(cal_begin.getTime()); strbuf.append(str_begin).append("\r\n"); // .append("~").append(str_end).append("\r\n"); cal_begin.add(Calendar.MONTH, 1); cal_begin.set(Calendar.DAY_OF_MONTH, 1); // String str_end =; } return strbuf.toString(); }
public static String getMonthEnd(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.MONTH, 1); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.add(Calendar.DAY_OF_YEAR, -1); return formatDateByFormat(calendar.getTime(), "yyyy-MM-dd"); }
public static String formatDateByFormat(Date date, String format) { String result = ""; if (date != null) { try { SimpleDateFormat sdf = new SimpleDateFormat(format); result = sdf.format(date); } catch (Exception ex) { ex.printStackTrace(); } } return result; }
整理筆記.