代码
public static void main(String[] args) {
try {
System.out.println(check(string2Date("2010-4-29"),string2Date("2011-6-4")));
} catch (Exception e) {
e.printStackTrace();
}
}
public static int check(Date beginDate, Date endDate) throws Exception {
Calendar cal = Calendar.getInstance();
cal.setTime(beginDate);
Integer beginYear = cal.get(Calendar.YEAR);
cal.setTime(endDate);
Integer endYear = cal.get(Calendar.YEAR);
if (beginYear == endYear) {
return betweenDaysInSameYear(beginDate, endDate);
} else {
int sumDays = 0;
for (Integer i = beginYear; i <= endYear; i++) {
if (i == beginYear) {
sumDays += betweenDaysInSameYear(beginDate, string2Date(i.toString()+ "-12-31"));
} else if (i == endYear) {
sumDays += betweenDaysInSameYear(string2Date(i.toString()+ "-1-1"), endDate);
} else {
sumDays += betweenDaysInSameYear(string2Date(i.toString()+ "-1-1"), string2Date(i.toString() + "-12-31"));
}
}
return sumDays;
}
}
public static int betweenDaysInSameYear(Date beginDate, Date endDate) {
Calendar cal = Calendar.getInstance();
cal.setTime(beginDate);
int beginWeek = cal.get(Calendar.WEEK_OF_YEAR);
int beginDay = cal.get(Calendar.DAY_OF_WEEK);
cal.setTime(endDate);
int endWeek = cal.get(Calendar.WEEK_OF_YEAR);
int endDay = cal.get(Calendar.DAY_OF_WEEK);
int beginDays = 0;
int endDays = 0;
switch (beginDay) {
case Calendar.SATURDAY:
beginDays = 0;
break;
case Calendar.SUNDAY:
beginDays = 0;
break;
default:
beginDays = Calendar.FRIDAY - beginDay + 1;
break;
}
switch (endDay) {
case Calendar.SATURDAY:
endDays = 5;
break;
case Calendar.SUNDAY:
endDays = 5;
break;
default:
endDays = endDay - 1;
break;
}
return beginDays+ ((endWeek - beginWeek - 2) * 5 < 0 ? 0 : ((endWeek- beginWeek - 2) * 5)) + endDays;
}
public static Date string2Date(String dateStr) throws Exception {
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
return fmt.parse(dateStr);
}