10

how can i define NSTimeInterval to mm:ss format?

iOS_User
  • 1,372
  • 5
  • 21
  • 35
  • possible duplicate of http://stackoverflow.com/questions/1189252/how-to-convert-an-nstimeinterval-seconds-into-minutes – kennytm Apr 01 '10 at 08:18

2 Answers2

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