Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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

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

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

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.

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

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];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top