Swift supports remainder calculations on floating-point numbers, so we can use % 1
.
var ms = Int((interval % 1) * 1000)
as in:
func stringFromTimeInterval(interval: TimeInterval) -> NSString {
let ti = NSInteger(interval)
let ms = Int((interval % 1) * 1000)
let seconds = ti % 60
let minutes = (ti / 60) % 60
let hours = (ti / 3600)
return NSString(format: "%0.2d:%0.2d:%0.2d.%0.3d",hours,minutes,seconds,ms)
}
result:
stringFromTimeInterval(12345.67) "03:25:45.670"
Swift 4:
extension TimeInterval{
func stringFromTimeInterval() -> String {
let time = NSInteger(self)
let ms = Int((self.truncatingRemainder(dividingBy: 1)) * 1000)
let seconds = time % 60
let minutes = (time / 60) % 60
let hours = (time / 3600)
return String(format: "%0.2d:%0.2d:%0.2d.%0.3d",hours,minutes,seconds,ms)
}
}
Use:
self.timeLabel.text = player.duration.stringFromTimeInterval()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…