将纳秒转换为毫秒不起作用

时间:2015-08-21 19:53:08

标签: ios swift nsdate nscalendar milliseconds

我试图从NSCalendarUnit获得毫秒数。我能够获得纳秒,但这个数字太多了。我想要的只是2个数字。这是我的代码:

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

let millisecond = Double(dateComponents.nanosecond)/1000000
let strFraction = String(format: "%02d", round(millisecond)
timeLabel.text = "\(strFraction)"

timeLabel显示00,这不是它应该显示的内容。如何从NSCalendar显示毫秒?

1 个答案:

答案 0 :(得分:0)

以下对我有用(某些XCode7更改......):

var startDate = NSDate()
let dateComponents = NSCalendar.currentCalendar().components(NSCalendarUnit.Nanosecond, fromDate: startDate, toDate: NSDate(), options: NSCalendarOptions(rawValue: 0))

let millisecond = Int(Double(dateComponents.nanosecond)/1000000 + 0.5)
let strFraction = String(format: "%02d", millisecond)