Hi
I'm writing a survey tool package and have to work out how long an
interview takes.
I'm having trouble working out how to work out the time taken between
a start time and end time.
I know in most cases if you subtrack the start time from the end time
t leaves you with the time taken. However consider st = 9.55 end time
= 10.05 tt = 10min but if I subtract them I'll get 1.10m.
Can anyone help me with a algorithm to do this?
Why don't you create a Time class where a time is represented by hours
and minutes instead of using doubles? That would be the logical thing
to do, because in abstract 9.55 does not equal "nine fifty-five". It
represents (9/24)hrs and (55/60)mins and you would probably be best off
to treat it as such. So in your new class, have two variables, minutes
and hours and initialize them when you create a new time, ala:
class Time {
static final MINS_IN_HOUR = 60;
int hours = 0;
int minutes = 0;
int hourFormat = 0;
public Time(int hours, int minutes, int hourFormat) {
this.hours = hours;
this.minutes = minutes;
this.hourFormat = hourFormat // 12 or 24 hour format
}
public Time subtract(Time subtrahend) {
int hourOffset = 0;
int newHours = 0;
int newMinutes = 0;
hourOffset = (this.minutes < subtrahend.minutes) ? 0 : 1;
newMinutes = (MINS_IN_HOUR - this.minutes) + subtrahend.minutes;
newHours = subtrahend.hours - this.hours - hourOffset;
// Account for the case that the newMinutes add up to 60 ie. 5:20-6:40
if (newMinutes = MINS_IN_HOUR) {
newMinutes = 0;
newHours += 1;
}
return new Time(newHours, newMinutes;
}
public void toString() {
String hourFormatLabel = "";
if (hourFormat == 12) {
if (this.hours > 11 && this.hours < 24)
hourFormatLabel = "pm";
else
hourFormatLabel = "am";
return (this.hours % hoursFormat + ":" + this.minutes +
" " + hourFormatLabel);
}
}
I don't know if that'll work off-hand because I coded it off the top of my
grey matter, but I think that's what you're looking for.
Usage:
-------------------------------------------------
int militaryTime = 24;
Time st = new Time(9, 55, militaryTime); // 9:55
Time et = new Time(10, 5, militaryTime); // 10:05
Time tt = st.subtract(et);
-------------------------------------------------
or
-------------------------------------------------
int standard = 12;
Time st = new Time(9, 55, standard); // 9:55
Time et = new Time(10, 5, standard); // 10:05
Time tt = st.subtract(et);
-------------------------------------------------
So what this class does for you is give you a way to represent a time and
a way to represent a difference between times, because the two are
different. For example, 1hr 10mins is not the same as 1:10pm, but they
can both be represented with this class. Hope that helps you!