问题
I am trying to calculate the minutes between two Joda DateTimes or Calendars in Java. Ofcourse this would be simple if I could use the Minutes.minutesBetween function, but I can only count the minutes between working days and 8:00 AM - 6:00 PM.
E.g.:
Startdate: 03-11-2015 16:00
Enddate: 03-11-2015 17:00
This would be simple, as it would be exactly 60 minutes. Because it's a workday and between the given work hours.
Now what I am trying to calculate is:
Startdate: 03-11-2015 17:00
Enddate: 03-12-2015 09:00
This should return 120 minutes even though there's a lot more minutes in between, because there's only two working hours between the two dates.
Sometimes there's also a weekend between two dates, those minutes should not be added either.
I have been trying tirelessly to implement this, but I have not found a solution.
Any ideas?
Thanks in advance.
EDIT: Thanks to Davis Broda's pseudocode I have found a solution:
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;
}
回答1:
a pseudocode solution might look something like the below.
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
来源:https://stackoverflow.com/questions/28995301/get-minutes-between-two-working-days-in-java