Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
542 views
in Technique[技术] by (71.8m points)

objective c - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...