NSTimeInterval to HH:mm:ss?

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

    To "extend" Matthias Bauch's suggestion, in Swift I would make this a computed property of NSTimeInterval:

    extension NSTimeInterval {
      var stringValue: String {
        let interval = Int(self)
        let seconds = interval % 60
        let minutes = (interval / 60) % 60
        let hours = (interval / 3600)
        return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
      }
    }
    

    The advantage of this is it's attached to the NSTimeInterval type, not your view controller or wherever else you put that function. To use you'd go something like:

    let timeInterval = NSDate().timeIntervalSinceDate(start)        
    self.elapsedTimeLabel.text = timeInterval.stringValue
    

提交回复
热议问题