views:

46

answers:

1

OK,

Thanks to all of you that have helped with my quandry. However, there is one stumbling block - I need to factor in night shifts. For example, if the start time is 13h and the finish time is 2h - I want it to come up as 15h, not 11h. This is the code:

  -(IBAction)done:(id)sender {
  int result = (([startHours.text intValue] * 60) + [startMinutes.text intValue]) - 
  (([finishHours.text intValue] * 60) + [finishMinutes.text intValue]);

  int minutes = abs(result)%60;
  int hours = (abs(result) - minutes)/60;
  totalHours.text = [NSString stringWithFormat:@"%02d:%02d", hours, minutes];
  if (finishHours.text > startHours.text) {
    totalHours.text= [NSString stringWithFormat:@"%02d:%02d", hours, minutes];
  }
+1  A: 

First off you should be subtract the start from the end, not the other way around.

You want to use modular arithmetic:

-(IBAction)done:(id)sender {
int result = (([finishHours.text intValue] * 60) + [finishMinutes.text intValue]) - 
(([startHours.text intValue] * 60) + [startMinutes.text intValue]);

// Use modular arithmetic to find absolute time difference
result = (result + 24*60)%(24*60);

// Display answer
int minutes = result%60;
int hours = (result - minutes)/60;
totalHours.text = [NSString stringWithFormat:@"%02d:%02d", hours, minutes];
if (finishHours.text > startHours.text) {
  totalHours.text= [NSString stringWithFormat:@"%02d:%02d", hours, minutes];
}
pheelicks
I tried that, but if I put in 13h as a start and 2h as a finish, I get -11 instead of 13.
LawVS
I forgot C handles negative % like that... see updated answer
pheelicks
You are a star! Thank you so much, pheelicks. :)
LawVS