NSTimeInterval to HH:mm:ss?

后端 未结 12 1814
陌清茗
陌清茗 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:42

    Based on answer by @onmyway133 here is the Swift 4 version:

    func format(duration: TimeInterval) -> String {
        let formatter = DateComponentsFormatter()
        formatter.zeroFormattingBehavior = .pad
    
        if duration >= 3600 {
            formatter.allowedUnits = [.hour, .minute, .second];
        } else {
            formatter.allowedUnits = [.minute, .second];
        }
    
        return formatter.string(from: duration) ?? "";
    }
    

提交回复
热议问题