NSTimeInterval to HH:mm:ss?

后端 未结 12 1813
陌清茗
陌清茗 2020-12-04 08:53

If I have an NSTimeInterval that is set to say 200.0, is there a way to convert that into 00:03:20, I was thinking I could initialise an NSDate with it and then use NSDateFo

12条回答
  •  清歌不尽
    2020-12-04 09:39

    Swift 3 version of onmyway133's answer:

    import Foundation
    
    func format(_ duration: TimeInterval) -> String {
        let formatter = DateComponentsFormatter()
        formatter.zeroFormattingBehavior = .pad
        formatter.allowedUnits = [.minute, .second]
    
        if duration >= 3600 {
            formatter.allowedUnits.insert(.hour)
        }
    
        return formatter.string(from: duration)!
    }
    
    
    print(format(12)) // 0:12
    print(format(65)) // 1:05
    print(format(1750)) // 29:10
    print(format(3890)) // 1:04:50
    print(format(45720)) // 12:42:00
    

提交回复
热议问题