views:

48

answers:

1

I have app that is a basic timer. It tracks the number of seconds the app has run. I want to convert it so the seconds (NSUInteger) are displayed like: 00:00:12 hh:mm:ss. So I've read this post:

http://stackoverflow.com/questions/1528822/nsnumber-of-seconds-to-hours-minutes-seconds

From which I wrote this code:

NSDate *date = [NSDate dateWithTimeIntervalSince1970:[[self meeting] elapsedSeconds]];
     NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
     [formatter setDateFormat:@"hh:mm:ss"];

It works fine, but it starts out with 04:00:00. I'm not sure why. I also tried doing something like:

NSDate *date = [NSDate dateWithTimeIntervalSinceNow:[[self meeting] elapsedSeconds] * -1];
     NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
     [formatter setDateFormat:@"hh:mm:ss"];

Thinking that it would display the counter correctly, but it does a wierd 01:23:00, then just flops to 04:00:00 and stays there for the rest of the time.

MS

+2  A: 

This is similar to a previous answer about formatting time but doesn't require a date formatter because we aren't dealing with dates any more.

If you have the number of seconds stored as an integer, you can work out the individual time components yourself:

NSUInteger h = elapsedSeconds / 3600;
NSUInteger m = (elapsedSeconds / 60) % 60;
NSUInteger s = elapsedSeconds % 60;

NSString *formattedTime = [NSSString stringWithFormat:@"%u:%02u:%02u", h, m, s];
dreamlax