NSTimeInterval格式化

2020/12/16 22:22 · ios ·  · 0评论

我想将NSTimeInterval其格式化为00: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];

更新

从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

但是,我没有办法强迫它在一小时内输出两位数,因此,如果这对您很重要,则需要使用其他解决方案。

迅捷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"

@Michael Frederick的答案的Swift版本:

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)
本文地址:http://ios.askforanswer.com/nstimeintervalgeshihua.html
文章标签: ,   ,  
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!