好的,
感谢所有为我的quandry提供帮助的人。然而,有一个绊脚石 - 我需要考虑夜班。例如,如果开始时间是13h并且结束时间是2h - 我希望它出现为15h,而不是11h。这是代码:
-(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];
}
答案 0 :(得分:1)
首先,你应该从最后减去开始,而不是相反。
您想使用模运算:
-(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];
}