java获取两个日期之间的年月(yyyy-MM)和年月日(yyyy-MM-dd)

public List<String> processToYYYYMMDD(String date1,String date2){
    	List<String> timeList=new ArrayList<String>();
    	if(date1.equals(date2)){
    		timeList.add(date1);
		    return timeList;
		}
		
		String tmp;
		timeList.add(date1);
		if(date1.compareTo(date2) > 0){//确保 date1的日期不晚于date2
			tmp = date1; date1 = date2; date2 = tmp;
		}
		
		tmp = format.format(str2Date(date1).getTime() + 3600*24*1000);
		timeList.add(tmp);
        int num = 0; 
        while(tmp.compareTo(date2) < 0){        	        
        	num++;
        	tmp = format.format(str2Date(tmp).getTime() + 3600*24*1000);
        	timeList.add(tmp);
        }
//        if(num == 0)
//        	System.out.println("两个日期相邻!");
    	return timeList;
    }
    
    private Date str2Date(String str) {
		if (str == null) return null;
		try {
			return format.parse(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
    
    public String[] getAllMonths(String start, String end){
        String splitSign="-";
        String regex="\\d{4}"+splitSign+"(([0][1-9])|([1][012]))"; //判断YYYY-MM时间格式的正则表达式
        if(!start.matches(regex) || !end.matches(regex)) return new String[0];
        
        List<String> list=new ArrayList<String>();
        if(start.compareTo(end)==0){
        	String[] result=new String[1];
        	result[0]=start;
        	return result;
        }
        
        if(start.compareTo(end)>0){
            //start大于end日期时,互换
            String temp=start;
            start=end;
            end=temp;
        }
        
        String temp=start; //从最小月份开始
        while(temp.compareTo(start)>=0 && temp.compareTo(end)<=0){
            list.add(temp); //首先加上最小月份,接着计算下一个月份
            String[] arr=temp.split(splitSign);
            int year=Integer.valueOf(arr[0]);
            int month=Integer.valueOf(arr[1])+1;
            if(month>12){
                month=1;
                year++;
            }
            if(month<10){//补0操作
                temp=year+splitSign+"0"+month;
            }else{
                temp=year+splitSign+month;
            }
        }
        
        int size=list.size();
        String[] result=new String[size]; 
        for(int i=0;i<size;i++){
            result[i]=list.get(i);
        }
        return result;
    }

猜你喜欢

转载自jin8000608172.iteye.com/blog/2097815