NSTimeInterval Formatting

泄露秘密 提交于 2019-11-27 12:02:21
Michael Frederick
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);
Johan Kool

Since iOS 8.0 there is now NSDateComponentsFormatter which has a stringFromTimeInterval: method.

[[NSDateComponentsFormatter new] stringFromTimeInterval:timeInterval];

"Best" is subjective. The simplest way is this:

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

UPDATE

As of iOS 8.0 and Mac OS X 10.10 (Yosemite), you can use NSDateComponentsFormatter if you need a locale-compliant solution. Example:

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

However, I don't see a way to force it to output two digits for the hour, so if that's important to you, you'll need to use a different solution.

swift 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)
    }
}

Test code:

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

// output "26:40:00"

Change unitStyle to get different styles. like formatter.unitsStyle = .abbreviated get

output: "26h 40m 0s"

A Swift version of @Michael Frederick's answer :

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!