Addition of Hours and Minutes
Whats the best way to add together values which have units Hours.Minutes,
For example:
I'm currently storing the values as doubles (hours before the point, minutes after e.g. 1.30 = 1 Hr 30 Mins) - is there a better way?
3.59 (3 hours 59 minutes) + 1.30 (1 hour 30 minutes) should give an answer of 5.29.
Thanks
[350 byte] By [
aandyG] at [2007-9-26 1:29:39]

Try creating a class based on hours and minutes. I'm not sure you can do this with GregorianCalendar or any of the Date classes. For example, adding 4 o'clock to 8 o'clock pm will yield 0 hours (which isn't what you want).
class HoursAndMinutes
{
int hours;
int minutes;
public HoursAndMinutes(double hoursAndMinutes) {
hours = (int)hoursAndMinutes;
minutes = (int) ((hoursAndMinutes - hours)*100.0);
}
public double toDouble() {
return hours + minutes/100.0;
}
public void add(HoursAndMinutes hm) {
minutes+=hm.minutes;
if(minutes > 59) {
minutes -= 59;
hours = hours + hm.hours + 1;
}
else {
hours += hm.hours;
}
}
}
public class DoubleTime
{
public static void main(String[] args)
{
HoursAndMinutes hm1 = new HoursAndMinutes(3.59);
HoursAndMinutes hm2 = new HoursAndMinutes(1.30);
hm1.add(hm2);
System.out.println("hm1+hm2: " + hm1.toDouble());
}
}
Use java.util.Calendar.
To add 3 hours, 29 minutes to the current time and print the result:
int myHours = 3;
int myMinutes = 29;
Calendar cal = Calendar.getInstance();
cal.add( Calendar.HOUR_OF_DAY, myHours );
cal.add( Calendar.MINUTE, myMinutes );
System.out.println( cal.toString() );
--Davud