这是一种计算两个日期之间的天数的方法:
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;
}