views:

152

answers:

3

Hey guys,

I got help with correct calculation the other day but I've hit a block about how to implement it into code.

-(IBAction)done:(id)sender {
  int result = (([startHours.text intValue] * 60) + [startMinutes.text intValue]) - 
  (([finishHours.text intValue] * 60) + [finishMinutes.text intValue]);
  totalHours.text = [NSString stringWithFormat:@"%i", result / 60];
  if (result < 0) { 
    totalHours.text = [NSString stringWithFormat:@"%d", result * -1];
  }

The above is the code. However, in the text field it comes out as the total number of minutes. I want to covert it so it would show up as total hours and minutes (10.30). How would I do that in code?

+2  A: 

If result is a time in minutes:

int minutes = result%60
int hours = (result - minutes)/60
totalHours.text = [NSString stringWithFormat:@"%d.%d", hours, minutes];
pheelicks
Whereabouts in the code would I include it?
LawVS
Also, how would I factor in night shifts as in more than 12 hours?
LawVS
A: 

Try changing the int to a float.

-(IBAction)done:(id)sender {
  float result = (([startHours.text intValue] * 60) + [startMinutes.text intValue]) - 
  (([finishHours.text intValue] * 60) + [finishMinutes.text intValue]);
  totalHours.text = [NSString stringWithFormat:@"%2.2f", result / 60];
  if (result < 0) { 
    totalHours.text = [NSString stringWithFormat:@"%2.2f", result * -1];
  }
Jordan
+1  A: 

Pheelicks's answer is OK. Just two small additions: handle sign of interval before calculating parts, and use more common time format:

  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];
Vladimir
How would I factor in night shifts? As in Start Hour equals 13h and the Finish hour equals 2h. I get 11 hours which is wrong, it should be 15 hours.
LawVS
if your time interval within one application session and start time always less than finish time, just do sign check before calculating partsif (result < 0) result += 12*60;
Vladimir
So how would I put in code?
LawVS