Formatting seconds into hh:ii:ss

2019-01-18 12:56发布

问题:

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

回答1:

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


回答2:

While there are easier ways of doing this (@dreamlax has a very good way), let me explain what is wrong with your example and let's get it working:

First, the reason that it is showing 04:00:00 (well, it is probably actually showing 04:00:12) is because it is converting the time from UTC/GMT to your local time. To fix this, you need to add the following line:

[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

Then, it will no longer show 04:00:12 because it doesn't convert the timezone. Unfortunately, it will now show 12:00:12 instead of 00:00:12 because it is midnight. In order to fix that, have it convert the string to 24 hour time instead by using the HH formatter instead of hh:

[formatter setDateFormat:@"HH:mm:ss"];

Keep in mind that since this was designed to work with times, that it will not work for more than 24 hours (because it will "roll over" to midnight again).

The full code would be:

NSDate *date = [NSDate dateWithTimeIntervalSince1970:[[self meeting] elapsedSeconds]];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm:ss"];
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

NSLog(@"%@", [formatter stringFromDate:date]);
// Results:  00:00:12