思路参考自文章:http://www.oschina.net/code/snippet_8676_2035
特别注意:Calender初始化时会根据当前时间初始化,所以就算设置了年月日,其时分秒部分仍然有值。对于比较同一天的情况下,.after()与.before()函数会将两个日期转换成整数比较,就算年月日相同,时分秒部分仍然后影响比较结果。因此推荐new Calender后执行一次.clear(),将对象清理一次,然后set年月日。
/**
*
* @param beginDate "yyyyMMdd"
* @param endDate "yyyyMMdd"
* @param schedule 对应星期几,可包含:1234567
* @return "yyyyMMdd yyyyMMdd yyyyMMdd ..."
*/
public static String parseDateBetweenTwoDates(String beginDate, String endDate, String schedule){
String retVal="";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
List<Integer> scheduleList = getDayOfWeek(schedule);
int year=0;
int month=0;
int day=0;
Calendar calendar_begin = new GregorianCalendar();
year = Integer.valueOf(beginDate.substring(0, 4));
month = Integer.valueOf(beginDate.substring(4, 6))-1;
day = Integer.valueOf(beginDate.substring(6));
calendar_begin.set(year, month, day);
Calendar calendar_end = new GregorianCalendar();
year = Integer.valueOf(endDate.substring(0, 4));
month = Integer.valueOf(endDate.substring(4, 6))-1;
day = Integer.valueOf(endDate.substring(6));
calendar_end.set(year, month, day);
calendar_end.add(Calendar.DAY_OF_YEAR,1);
while(calendar_begin.before(calendar_end)){
if( scheduleList.contains(calendar_begin.get(Calendar.DAY_OF_WEEK)) ) {
retVal += dateFormat.format(new Date(calendar_begin.getTime().getTime())) + " ";
}
calendar_begin.add(Calendar.DAY_OF_YEAR,1);
}
return retVal.trim();
}
/**
*
* @param schedule:1234567
* @return {0,1,2,3,4,5,6}
*/
private static List<Integer> getDayOfWeek(String schedule){
List<Integer> retList = new ArrayList<Integer>();
if(schedule.contains("7")) retList.add(1);
if(schedule.contains("1")) retList.add(2);
if(schedule.contains("2")) retList.add(3);
if(schedule.contains("3")) retList.add(4);
if(schedule.contains("4")) retList.add(5);
if(schedule.contains("5")) retList.add(6);
if(schedule.contains("6")) retList.add(7);
return retList;
}