2つの日付の間の日数を計算する方法は次のとおりです。
private int calculateNumberOfDaysBetween(Date startDate, Date endDate) {
if (startDate.after(endDate)) {
throw new IllegalArgumentException("End date should be grater or equals to start date");
}
long startDateTime = startDate.getTime();
long endDateTime = endDate.getTime();
long milPerDay = 1000*60*60*24;
int numOfDays = (int) ((endDateTime - startDateTime) / milPerDay); // calculate vacation duration in days
return ( numOfDays + 1); // add one day to include start date in interval
}
そして、これが指定された期間の週の日数を計算するメソッドです:
private static int calculateNumberOfWeekendsInRange(Date startDate, Date endDate) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
int counter = 0;
while(!calendar.getTime().after(endDate)) {
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek==1 || dayOfWeek==7) {
counter++;
}
calendar.add(Calendar.DAY_OF_MONTH, 1);
}
return counter;
}
編集:
最後の方法を変更しました。週末を除く日数を計算するようになりました。
private int calculateNumberOfDaysExcludeWeekends(Date startDate, Date endDate) {
if (startDate.after(endDate)) {
throw new IllegalArgumentException("End date should be grater or equals to start date");
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
int numOfDays = 0;
while(!calendar.getTime().after(endDate)) {
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
if ( (dayOfWeek>1) && (dayOfWeek<7) ) {
numOfDays++;
}
calendar.add(Calendar.DAY_OF_MONTH, 1);
}
return numOfDays;
}