iSofTom
iSofTom

Reputation: 1718

How to display number as an hour from duration in iOS?

Is there a way to display a number as an hour from a duration ? For example i have a NSTimeInterval value containing 127 and i want to display 02:07.

What's the better way to do that ? Thanks.

Upvotes: 2

Views: 873

Answers (2)

Dustin
Dustin

Reputation: 6803

value = (int) othervalue;    
NSString *str = [NSString stringWithFormat:@"%2d:%2d",value/60,value%60];
  • The value/60 does integer division on the number, which throws out anything < 0. So 127 / 60 gives you 2.
  • % (modulo) gives the remainder of division: 127 % 60 gives you 7.

The casting to int keeps you from getting an error from a float or double value (thanks for the comment holex).

And the %2d gives you 2-digit format (thanks for the other comment Rene Jennrich).

Upvotes: 0

holex
holex

Reputation: 24041

Enjoy! :)

NSTimeInterval _timeInterval = 127.f;

NSInteger _hours = _timeInterval / 60;
NSInteger _minutes = (NSInteger)_timeInterval % 60; 

NSLog(@"%02d:%02d", _hours, _minutes);

Upvotes: 9

Related Questions