/**
* 获取某段时间内周几的日期,比如周一、周二...
* @param beginDate 开始日期
* @param endDate 结束日期
* @param weekDays 周几-可指定多个。1-6代表周一到周六,0代表周日
* @return 返回日期集合
*/
public static List<String> getDayOfWeekWithinDateInterval(String beginDate, String endDate, int... weekDays{
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
List<String> dateResult = new ArrayList<>();
Calendar cal = Calendar.getInstance();
String[] dateInterval = {beginDate, endDate};
Date[] dates = new Date[dateInterval.length];
for (int i = 0; i < dateInterval.length; i++) {
String[] ymd = dateInterval[i].split("[^\\d]+");
cal.set(Integer.parseInt(ymd[0]), Integer.parseInt(ymd[1]) - 1, Integer.parseInt(ymd[2]));
dates[i] = cal.getTime();
}
for (Date date = dates[0]; date.compareTo(dates[1]) <= 0; ) {
cal.setTime(date);
for (int weekDay : weekDays) {
if (cal.get(Calendar.DAY_OF_WEEK) - 1 == weekDay) {
String format = formater.format(date);
dateResult.add(format);
}
}
cal.add(Calendar.DATE, 1);
date = cal.getTime();
}
return dateResult;
}
public static void main(String[] args) {
List<String> dayOfWeekWithinDateInterval = getDayOfWeekWithinDateInterval("2023-05-15", "2023-06-19", 1,4);
System.out.println(dayOfWeekWithinDateInterval);
List<String> dayOfWeekWithinDateInterval = getDayOfWeekWithinDateInterval(
args[0],
args[1],
Arrays.stream(args[2].split(","))
.map(Integer::parseInt)
.toArray(Integer[]::new));
System.out.println(dayOfWeekWithinDateInterval);
}