一尘不染

从NSTimeInterval迅速转换为时,分,秒,毫秒

swift

我的代码在这里:

func stringFromTimeInterval(interval:NSTimeInterval) -> NSString {

    var ti = NSInteger(interval)
    var ms = ti * 1000
    var seconds = ti % 60
    var minutes = (ti / 60) % 60
    var hours = (ti / 3600)

      return NSString(format: "%0.2d:%0.2d:%0.2d",hours,minutes,seconds,ms)
}

在输出中毫秒数会给出错误的结果。请给出一个如何正确找到毫秒数的想法。


阅读 1935

收藏
2020-07-07

共1个答案

一尘不染

Swift支持对浮点数进行余数计算,因此我们可以使用% 1

var ms = Int((interval % 1) * 1000)

如:

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)
}

结果:

stringFromTimeInterval(12345.67)                   "03:25:45.670"

斯威夫特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)

        }
    }

用:

self.timeLabel.text = player.duration.stringFromTimeInterval()
2020-07-07