此方法是基于获取两个日期之间星期几所在的日期列表的需求 。
例如:2012-06-01到2012-07-01之间,星期四和星期五所在的日期。
代码如下:
/**
* 获取指定时间段内,特定星期几的日期字符串列表
* @param begin 开始日期 格式为:2012/12/12
* @param end 结束日期 格式为:2012/12/12
* @param week 要选择的星期 为本周的第几天,以星期日为 本周的第“1”天
* @return 日期字符串列表
*/
public static List getMeetingDate(String begin, String end, String[] week) {
String beginStr = begin.replaceAll("\\/", "-");
String endStr = end.replaceAll("\\/", "-");
List list = new ArrayList();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINESE);
Calendar beginDate = Calendar.getInstance();
Calendar endDate = Calendar.getInstance();
try {
beginDate.setTime(dateFormat.parse(beginStr));
endDate.setTime(dateFormat.parse(endStr));
} catch (ParseException e) {
e.printStackTrace();
}
//获取指定日历的副本
Calendar date = (Calendar)beginDate.clone();
while(date.before(endDate)) {
//获取日期所在周的第几天
int dayOfWeek = date.get(Calendar.DAY_OF_WEEK);
for(int i = 0; i < week.length; i++) {
if(dayOfWeek == Integer.parseInt(week[i])) {
String str = dateFormat.format(date.getTime());
list.add(str);
}
}
//日期的后一天
date.add(Calendar.DAY_OF_MONTH, 1);
}
return list;
}
返回的是日期字符串列表