views:

390

answers:

2

Hi there,

I am struggling with this. I have a value in seconds that I want to display in a label in HH:MM format. I have searched the internet for ages and found some answers, but either not fully understood them, or they seem like an odd way of doing what I want. If someone could help me out on this one that would be great! Bear in mind that I am new to this games so this question may seem like a really basic one to the more experienced out there.

+7  A: 

I was looking for the same thing that you are looking but couldn't find one. So I wrote one -

- (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]; 
}
Rohit Agarwal
Thanks for your answer, it looks like what I need, but can't seem to use it without errors. I am convinced the error is on my side. If you don't mind helping me further:My value is a float and it is in seconds. I have it displaying in a label when a button is pressed. Where would your code go, and how would I make my label display the value in the HH:MM format? Many thanks,Stu
Stumf
Sorted, thanks for your help. Your answer and http://stackoverflow.com/questions/1259028/convert-nsnumber-double-value-into-timeanswer by Pholker were the reason I could do this! Thanks again
Stumf
by far, the cleanest approach i've seen (+1)
bitcruncher
Great stuff -- made this a class method and rolled it into a category on NSString. Agree with bitcruncher, very clean.
Danilo Campos
+1  A: 

Take a look at a similar question I asked a while ago which also covers the aspect of memory and efficiency.

Jorge Israel Peña