我试图通过忽略周末来获得两个特定时间实例之间的分钟数。这就是我所做的。
public static final List<Integer> NON_WORKING_DAYS;
static {
List<Integer> nonWorkingDays = new ArrayList<Integer>();
nonWorkingDays.add(Calendar.SATURDAY);
nonWorkingDays.add(Calendar.SUNDAY);
NON_WORKING_DAYS = Collections.unmodifiableList(nonWorkingDays);
}
public static int getMinsBetween(Date d1, Date d2, boolean onlyBusinessDays)
{
int minsBetween = (int)((d2.getTime() - d1.getTime()) / (1000 * 60));
int minsToSubtract = 0;
if(onlyBusinessDays){
Calendar dateToCheck = Calendar.getInstance();
dateToCheck.setTime(d1);
Calendar dateToCompare = Calendar.getInstance();
dateToCompare.setTime(d2);
//moving the first day of the week to Tues so that a Sat, sun and mon fall in the same week, easy to adjust dates
dateToCheck.setFirstDayOfWeek(Calendar.TUESDAY);
dateToCompare.setFirstDayOfWeek(Calendar.TUESDAY);
//moving the dates out of weekends
if(!isBusinessDay(dateToCheck, NON_WORKING_DAYS)){
dateToCheck.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
dateToCheck.set(Calendar.HOUR, 0);
dateToCheck.set(Calendar.MINUTE, 0);
dateToCheck.set(Calendar.SECOND, 0);
dateToCheck.set(Calendar.MILLISECOND, 0);
}
if(!isBusinessDay(dateToCompare, NON_WORKING_DAYS)){
dateToCompare.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
dateToCompare.set(Calendar.HOUR, 0);
dateToCompare.set(Calendar.MINUTE, 0);
dateToCompare.set(Calendar.SECOND, 0);
dateToCompare.set(Calendar.MILLISECOND, 0);
}
for(; dateToCheck.getTimeInMillis() < dateToCompare.getTimeInMillis() ; dateToCheck.add(Calendar.DAY_OF_MONTH, 1)){
if(isBusinessDay(dateToCheck, NON_WORKING_DAYS)){
minsToSubtract = minsToSubtract + 1440;
}
}
minsBetween = minsBetween - minsToSubtract;
}
return minsBetween;
}
private static boolean isBusinessDay(Calendar dateToCheck, List<Integer> daysToExclude){
for(Integer dayToExclude : daysToExclude){
if(dayToExclude != null && dayToExclude == dateToCheck.get(Calendar.DAY_OF_WEEK)) {
return true;
}
else continue;
}
return false;
}
有人可以告诉我我的逻辑是否正确,如果不正确,该怎么做?我不太确定当周末月份发生变化时这段代码会如何表现。
一些测试用例的预期输出:
- 周五下午 6 点,周一早上 6 点 - 应该返回 12 小时
- 星期六 12 pm,星期日 12 pm - 应该返回 0 小时
- 周六中午 12 点,周一早上 6 点 - 应该返回 6 小时