-3

I have the duration of a song in seconds.

After following calculations, I have the time in hour, minutes and seconds.

int hour = time / 3600;
int minute = (time / 60) % 60;
int second = time % 60;

I need to show them with this format HH:mm:ss

How can I do that?

aakpro
  • 1,538
  • 2
  • 19
  • 53

6 Answers6

3

It could be helpful

- (NSString *)timeFormatted:(int)totalSeconds
{

    int seconds = totalSeconds % 60; 
    int minutes = (totalSeconds / 60) % 60; 
    int hours = totalSeconds / 3600; 

    return [NSString stringWithFormat:@"%02d:%02d:%02d",hours, minutes, seconds]; 
}
Tendulkar
  • 5,550
  • 2
  • 27
  • 53
2

You needn't to use a NSDateFormatter according to your description

int hour = time / 3600;
int minute = (time / 60) % 60;
int second = time % 60;

NSString *yourDate = [NSString stringWithFormat:@"%02d:%02d:%02d", hour, minute, second, null];
Jerome Diaz
  • 1,746
  • 8
  • 15
  • Does it make the correct format for all of cases? – aakpro Sep 03 '13 at 06:53
  • yes : '%02d' display a int with at least two digits, adding '0' before if necessary : 0 becomes '00', 1 becomes '01', ... when the number is greater than 9 it remains unchanged – Jerome Diaz Sep 03 '13 at 07:59
2

This will append 0 and make it exactly 2 characters..

NSString *str = [NSString stringWithFormat:@"%02d:%02d:%02d",hour,minute,second ];
TorukMakto
  • 2,066
  • 2
  • 24
  • 38
1

Try it

int hour = time / 3600;
int minute = (time / 60) % 60;
int second = time % 60;

 NSString *dateStr = [NSString stringWithFormat:@"%d %d %d",hour,minute,second];

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"HH:mm:ss"];
    NSDate *date1 = [dateFormat dateFromString:dateStr];

Hope it will help you.

Tamnna
  • 250
  • 2
  • 10
  • Why create a date from the string? Not to mention that the date format you gave doesn't match the string. – rmaddy Sep 03 '13 at 06:54
0
NSString *time = [NSString stringWithFormat:@"%d:%d:%d", hour, minute, second];
Lokesh Chowdary
  • 816
  • 5
  • 22
0

Try this code

   float seconds = totalSeconds % 60; 
   float minutes = (totalSeconds / 60) % 60; 
   float hours = totalSeconds / 3600; 
   return [NSString stringWithFormat:@"%02f:%02f:%02f",hours, minutes, seconds];
NANNAV
  • 4,875
  • 4
  • 32
  • 50