【问题标题】:Convert nanosecond to millisecond not working将纳秒转换为毫秒不起作用
【发布时间】:2015-08-21 19:53:07
【问题描述】:

我正在尝试从 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 获得毫秒显示?

【问题讨论】:

    标签: ios swift nsdate nscalendar milliseconds


    【解决方案1】:

    以下内容对我有用(一些 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)
    

    【讨论】:

    • 终于!!!有用的东西!唯一的问题是,它显示了 3 个数字。我怎样才能让它只显示 2?
    • 3个数字是什么意思?例子?
    • 当然。毫秒范围为 0...999,因此除以 10000000(多一位),因为您似乎在小数点后输出它 :-) 也许您应该将它从 10* 毫秒开始计算为十秒,或者只是小数秒。
    • 当然必须命名为厘秒(第 100 秒)而不是十秒(第 10 秒);-)
    猜你喜欢
    • 2015-11-14
    • 2016-07-16
    • 2020-02-01
    • 1970-01-01
    • 2011-05-17
    • 2017-06-19
    • 2013-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多