如何将纳秒转换为毫秒

Hor*_*ray 4 nsdate milliseconds nscalendar ios swift

我正试图millisecondsNSCalendarUnit. 我能够得到nanosecond,但是数字太多了。我想要的只是 2 个数字。这是我的代码:

var startDate = NSDate()
let dateComponents = NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitNanosecond, fromDate: startDate, toDate: NSDate(), options: nil)

let strFraction = String(format: "%02d", dateComponents.nanosecond)
timeLabel.text = "\(strFraction)"
Run Code Online (Sandbox Code Playgroud)

如何从 NSCalendarUnit 获取毫秒?

Sen*_*con 5

由于没有Calendar.Component.millisecond,与 相反Calendar.Component.nanosecond,我们需要将纳秒转换为毫秒。1 毫秒等于 1000000 纳秒,因此您需要将纳秒数除以 1000000。如果您想要一个整数值,round(nanoseconds/1000000)