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:
开发者_Python百科 -(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];
}
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];
}
精彩评论