Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting seconds into hh:ii:ss

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:

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

like image 911
Mark Steudel Avatar asked Oct 28 '10 20:10

Mark Steudel


1 Answers

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 = [NSString stringWithFormat:@"%u:%02u:%02u", h, m, s];
like image 168
dreamlax Avatar answered Sep 23 '22 00:09

dreamlax