以月份为单位划分时间区间

public static List getTimeAreaList(String stime,String etime){
    List result = new ArrayList();
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    Date sdate = null;
    Date eDate = null;
    try {
        sdate = df.parse(stime);
        eDate = df.parse(etime);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    Calendar sc = Calendar.getInstance();
    sc.setTime(sdate);
    Calendar ec = Calendar.getInstance();
    ec.setTime(eDate);
    if(sc.get(Calendar.YEAR)==ec.get(Calendar.YEAR)&&sc.get(Calendar.MONTH)==ec.get(Calendar.MONTH)){
        result.add(stime+","+etime);
    }else{
        Calendar temp = Calendar.getInstance();
        temp.setTime(sdate);
        String y = String.valueOf(temp.get(Calendar.YEAR));
        String m = String.valueOf(temp.get(Calendar.MONTH)+1);
        String d = String.valueOf(temp.getActualMaximum(Calendar.DAY_OF_MONTH));
        m = m.length()==1?0+m:m;
        result.add(stime+","+y+"-"+m+"-"+d);
        temp.add(Calendar.MONTH,+1);
        while(true){
            if(temp.get(Calendar.YEAR)==ec.get(Calendar.YEAR)&&temp.get(Calendar.MONTH)==ec.get(Calendar.MONTH)){
                break;
            }
            String year = String.valueOf(temp.get(Calendar.YEAR));
            String month = String.valueOf(temp.get(Calendar.MONTH)+1);
            String days = String.valueOf(temp.getActualMaximum(Calendar.DAY_OF_MONTH));
            month = month.length()==1?0+month:month;
            result.add(year+"-"+month+"-01"+","+year+"-"+month+"-"+days);
            temp.add(Calendar.MONTH,+1);
        }
        String year = String.valueOf(ec.get(Calendar.YEAR));
        String month = String.valueOf(ec.get(Calendar.MONTH)+1);
        result.add(year+"-"+month+"-01"+","+df.format(eDate));
    }
    return  result;
}

你可能感兴趣的:(以月份为单位划分时间区间)