将纳秒转换为毫秒不起作用
Convert nanosecond to millisecond not working
我正在尝试从 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 中获取显示的毫秒数?
以下对我有用(一些 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)
我正在尝试从 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 中获取显示的毫秒数?
以下对我有用(一些 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)