我正在尝试计算Java中两个Joda DateTimes或Calendars之间的分钟数。 当然,如果我可以使用Minutes.minutesBetween函数,这将很简单,但我只计算工作日和上午8:00 - 下午6:00之间的分钟数。
E.g:
Startdate:03-11-2015 16:00
结束日期:03-11-2015 17:00
这很简单,因为它恰好是60分钟。因为这是一个工作日,在给定的工作时间之间。
现在我想要计算的是:
Startdate:03-11-2015 17:00
Enddate:03-12-2015 09:00
这应该会返回120分钟,即使两者之间有更多的分钟,因为两个日期之间只有两个工作小时。
有时在两个日期之间也会有一个周末,也不应该添加这些会议记录。
我一直在努力实现这一点,但我还没有找到解决方案。
有什么想法吗?
提前致谢。
编辑: 感谢Davis Broda的伪代码,我找到了一个解决方案:
private static int BEGINWORKHOUR = 8;
private static int ENDWORKHOUR = 16;
public int getWorkedMinutes(){
Calendar start = (Calendar) this.startTime.clone();
Calendar end = (Calendar) this.endTime.clone();
if(start.get(Calendar.HOUR_OF_DAY) < BEGINWORKHOUR){
start.set(Calendar.HOUR_OF_DAY, BEGINWORKHOUR);
start.set(Calendar.MINUTE, 0);
}
if(end.get(Calendar.HOUR_OF_DAY) >= ENDWORKHOUR){
end.set(Calendar.HOUR_OF_DAY, ENDWORKHOUR);
end.set(Calendar.MINUTE, 0);
}
int workedMins = 0;
while(!sameDay(start, end)){
workedMins += workedMinsDay(start);
start.add(Calendar.DAY_OF_MONTH, 1);
start.set(Calendar.HOUR_OF_DAY, BEGINWORKHOUR);
start.set(Calendar.MINUTE, 0);
}
workedMins += (end.get(Calendar.MINUTE) - start.get(Calendar.MINUTE)) + ((end.get(Calendar.HOUR_OF_DAY) - start.get(Calendar.HOUR_OF_DAY))*60);
return workedMins;
}
private int workedMinsDay(Calendar start){
if((start.get(Calendar.DAY_OF_WEEK) == 1) || (start.get(Calendar.DAY_OF_WEEK) == 6)) return 0;
else return (60 - start.get(Calendar.MINUTE)) + ((ENDWORKHOUR - start.get(Calendar.HOUR_OF_DAY) - 1)*60);
}
private boolean sameDay(Calendar start, Calendar end){
if(start.get(Calendar.YEAR) == end.get(Calendar.YEAR) && start.get(Calendar.MONTH) == end.get(Calendar.MONTH) &&
start.get(Calendar.DAY_OF_MONTH) == end.get(Calendar.DAY_OF_MONTH)) return true;
else return false;
}
答案 0 :(得分:3)
伪代码解决方案可能如下所示。
onSameWorkDay?
if yes
simple date comparison
if no
days = find number of whole work days between the two dates
dayToMin = days * 8 * 60
minDay1 = find minutes between specified start time and end of day1
minDay2 = find minutes between start of final day and specified end time
totalTime = dayToMin + minDay1 + minDay2