NSTimeInterval to HH:mm:ss?

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

    In Swift 2, iOS 8+. This makes sure we only show hour when necessary

    func format(duration: NSTimeInterval) -> String {
      let formatter = NSDateComponentsFormatter()
      formatter.zeroFormattingBehavior = .Pad
    
      if duration >= 3600 {
        formatter.allowedUnits = [.Hour, .Minute, .Second]
      } else {
        formatter.allowedUnits = [.Minute, .Second]
      }
    
      return formatter.stringFromTimeInterval(duration) ?? ""
    }
    

    So you have

    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
    

提交回复
热议问题