开发者

How do I convert a number to hours and minutes?

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] * 开发者_StackOverflow社区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?


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'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];


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];
  }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜