NSTimeInterval格式

我想采取我的NSTimeInterval并格式化为一个string00:00:00(小时,分钟,秒)。 做这个的最好方式是什么?

 NSTimeInterval interval = ...; NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval]; NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; [dateFormatter setDateFormat:@"HH:mm:ss"]; [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]]; NSString *formattedDate = [dateFormatter stringFromDate:date]; NSLog(@"hh:mm:ss %@", formattedDate); 

从iOS 8.0开始,现在有NSDateComponentsFormatter ,它有一个stringFromTimeInterval:方法。

 [[NSDateComponentsFormatter new] stringFromTimeInterval:timeInterval]; 

“最好”是主观的。 最简单的方法是这样的:

 unsigned int seconds = (unsigned int)round(myTimeInterval); NSString *string = [NSString stringWithFormat:@"%02u:%02u:%02u", seconds / 3600, (seconds / 60) % 60, seconds % 60]; 

UPDATE

从iOS 8.0和Mac OS X 10.10(Yosemite)开始,如果您需要符合语言环境的解决scheme,则可以使用NSDateComponentsFormatter 。 例:

 NSTimeInterval interval = 1234.56; NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init]; formatter.allowedUnits = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond; formatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorPad; NSString *string = [formatter stringFromTimeInterval:interval]; NSLog(@"%@", string); // output: 0:20:34 

但是,我没有办法强制它输出两位数的小时,所以如果这对你很重要,你需要使用不同的解决scheme。

@Michael Frederick的一个快速版本的答案:

 let duration: NSTimeInterval = ... let durationDate = NSDate(timeIntervalSince1970: duration) let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "HH:mm:ss" dateFormatter.timeZone = NSTimeZone(name: "UTC") let durationString = dateFormatter.stringFromDate(durationDate)