NSTimeInterval格式

时间:2011-11-14 21:04:03

标签: objective-c ios nstimeinterval

我想带我的NSTimeInterval并将其格式化为字符串00:00:00(小时,分钟,秒)。这样做的最佳方式是什么?

5 个答案:

答案 0 :(得分:105)

自iOS 8.0起,现在NSDateComponentsFormatter有一个stringFromTimeInterval:方法。

[[NSDateComponentsFormatter new] stringFromTimeInterval:timeInterval];

答案 1 :(得分:60)

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

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

更新

从iOS 8.0和Mac OS X 10.10(Yosemite)开始,如果您需要符合区域设置的解决方案,则可以使用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

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

答案 2 :(得分:27)

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

答案 3 :(得分:0)

Swift版本的@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)

答案 4 :(得分:0)

迅速4.2

extension Date {
    static func timestampString(timeInterval: TimeInterval) -> String? {
        let formatter = DateComponentsFormatter()
        formatter.unitsStyle = .positional
        formatter.zeroFormattingBehavior = .pad
        formatter.maximumUnitCount = 0
        formatter.allowedUnits = [.hour, .minute, .second]
        return formatter.string(from: timeInterval)
    }
}

测试代码:

let hour = 60 * 50 * 32
Date.timestampString(timeInterval: TimeInterval(hour))

// output "26:40:00"

更改unitStyle以获取不同的样式。像formatter.unitsStyle = .abbreviated得到

输出:"26h 40m 0s"