how can i define NSTimeInterval to mm:ss format?
Asked
Active
Viewed 1.3k times
10
-
possible duplicate of http://stackoverflow.com/questions/1189252/how-to-convert-an-nstimeinterval-seconds-into-minutes – kennytm Apr 01 '10 at 08:18
2 Answers
30
NSTimeInterval interval = 326.4;
long min = (long)interval / 60; // divide two longs, truncates
long sec = (long)interval % 60; // remainder of long divide
NSString* str = [[NSString alloc] initWithFormat:@"%02d:%02d", min, sec];
The %02d format specifier gives you a 2 digit number with a leading zero.
Note: this is for positive values of interval only.

progrmr
- 75,956
- 16
- 112
- 147
-
just take the absolute value of the interval, then do the math so it works for negative values also. +1 for good solution! – Sam Sep 08 '11 at 14:28
2
See this question.
Accepted answer by Brian Ramsay is:
Given 326.4 seconds, pseudo-code:
minutes = floor(326.4/60)
seconds = round(326.4 - minutes * 60)
If you print with %02d
, you will get e.g. 03:08
if either number is less than 10.

Community
- 1
- 1

Chris Cooper
- 17,276
- 9
- 52
- 70
-
with "%2d" you would get " 3: 8", you want %02d instead to get the leading zero. – progrmr Mar 22 '13 at 16:22
-
Thanks for pointing this out @progrmr; I haven't looked back at this answer in a while to see the imbalance. – Chris Cooper Mar 23 '13 at 05:41